Discovering the Collections Framework

1. A collection is a group of objects that are stored in an instance of a class designed for this purpose.

2. The collections framework is a standardized architecture for representing and manipulating collections.

3. The collections framework largely consists of core interfaces, implementation classes, and utility classes.

4. A comparable is an object whose class implements the Comparable interface.

5. You would have a class implement the Comparable interface when you want objects to be compared according to their natural ordering.

6. A comparator is an object whose class implements the Comparator interface. Its purpose is to allow objects to be compared according to an order that is different from their natural ordering.

7. The answer is false: a collection uses a comparable (an object whose class implements the Comparable interface) to define the natural ordering of its elements.

8. The Iterable interface describes any object that can return its contained objects in some sequence.

9. The Collection interface represents a collection of objects that are known as elements.

10. A situation where Collection's add() method would throw an instance of the UnsupportedOperationException class is an attempt to add an element to an unmodifiable collection.

11. Iterable's iterator() method returns an instance of a class that implements the Iterator interface. This interface provides a hasNext() method to determine if the end of the iteration has been reached, a next() method to return a collection's next element, and a remove() method to remove the last element returned by next() from the collection.

12. The purpose of the enhanced for loop statement is to simplify collection or array iteration.

13. The enhanced for loop statement is expressed as for (type id: collection) or for (type id: array) and reads "for each type object in collection, assign this object to id at the start of the loop iteration" or "for each type object in array, assign this object to id at the start of the loop iteration."

14. The answer is true: the enhanced for loop works with arrays. For example, int [] x = { 1, 2, 3 }; for (int i: x) System.out.println(i); declares arrayx and outputs all of its int-based elements.

15. Autoboxing is the act of wrapping a primitive value in an object of a primitive wrapper class type whenever a primitive type is specified but a reference is required. This feature saves the developer from having to explicitly instantiate a wrapper class when storing the primitive value in a collection.

16. Unboxing is the act of unwrapping a primitive value from its wrapper object whenever a reference is specified but a primitive type is required. This feature saves the developer from having to explicitly call a method on the object (such as intValue()) to retrieve the wrapped value.

17. A list is an ordered collection, which is also known as a sequence. Elements can be stored in and accessed from specific locations via integer indexes.

18. A ListIterator instance uses a cursor to navigate through a list.

19. A view is a list that is backed by another list. Changes that are made to the view are reflected in this backing list.

20. You would use the subList() method to perform range-view operations over a collection in a compact manner. For example, list.subList(fromIndex, toIndex).clear(); removes a range of elements from list where the first element is located at fromIndex and the last element is located at toIndex-1.

21. The ArrayList class provides a list implementation that is based on an internal array.

22. The LinkedList class provides a list implementation that is based on linked nodes.

23. A node is a fixed sequence of value and link memory locations.

24. The answer is false: ArrayList provides slower element insertions and deletions than LinkedList.

25. A set is a collection that contains no duplicate elements.

26. The TreeSet class provides a set implementation that is based on a tree data structure. As a result, elements are stored in sorted order.

27. The HashSet class provides a set implementation that is backed by a hashtable data structure.

The answer is true: to avoid duplicate elements in a hashset, your own classes must correctly override equals() and hashCode().

The difference between HashSet and LinkedHashSet is that LinkedHashSet uses a linked list to store its elements, resulting in its iterator returning elements in the order in which they were inserted.

The EnumSet class provides a Set implementation that is based on a bitset.

A sorted set is a set that maintains its elements in ascending order, sorted according to their natural ordering or according to a comparator that is supplied when the sorted set is created. Furthermore, the set's implementation class must implement the SortedSet interface.

The answer is false: HashSet is not an example of a sorted set. However, TreeSet is an example of a sorted set.

A sorted set's add() method would throw ClassCastException when you attempt to add an element to the sorted set because the element's class does not implement Comparable.

A queue is a collection in which elements are stored and retrieved in a specific order. Most queues are categorized as "first-in, first out," "last-in, first-out," or priority.

The answer is true: Queue's element() method throws NoSuchElementException when it is called on an empty queue.

The PriorityQueue class provides an implementation of a priority queue, which is a queue that orders its elements according to their natural ordering or by a comparator provided when the queue is instantiated.

A map is a group of key/value pairs (also known as entries).

The TreeMap class provides a map implementation that is based on a red-black tree. As a result, entries are stored in sorted order of their keys.

The HashMap class provides a map implementation that is based on a hashtable data structure.

A hashtable uses a hash function to map keys to integer values.

Continuing from the previous exercise, the resulting integer values are known as hash codes; they identify hashtable array elements, which are known as buckets or slots.

A hashtable's capacity refers to the number of buckets.

A hashtable's load factor refers to the ratio of the number of stored entries divided by the number of buckets.

44. The difference between HashMap and LinkedHashMap is that LinkedHashMap uses a linked list to store its entries, resulting in its iterator returning entries in the order in which they were inserted.

45. The IdentityHashMap class provides a Map implementation that uses reference equality (==) instead of object equality (equals()) when comparing keys and values.

46. The WeakHashMap class provides a Map implementation that is based on weakly reachable keys.

47. The EnumMap class provides a Map implementation whose keys are the members of the same enum.

48. A sorted map is a map that maintains its entries in ascending order, sorted according to the keys' natural ordering or according to a comparator that is supplied when the sorted map is created. Furthermore, the map's implementation class must implement the SortedMap interface.

49. The answer is true: TreeMap is an example of a sorted map.

50. The purpose of the Arrays class's static <T> List<T> asList(T... array) method is to return a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)

51. The answer is false: binary search is faster than linear search.

52. You would use Collections' static <T> Set<T> synchronizedSet(Set<T> s) method to return a synchronized variation of a hashset.

53. The seven legacy collections-oriented types are Vector, Enumeration, Stack, Dictionary, Hashtable, Properties, and BitSet.

54. Listing 36 presents the JavaQuiz application's JavaQuiz source file that was called for in Chapter 8.

Listing 36. How much do you know about Java? Take the quiz and find out!

public class JavaQuiz {

static QuizEntry[] quizEntries = {

new QuizEntry("What was Java's original name?", new String[] { "Oak", "Duke", "J", "None of the above" }, 'A'), new QuizEntry("Which of the following reserved words is also a literal?", new String[] { "for", "long", "true", "enum" }, 'C'), new QuizEntry("The conditional operator (?:) resembles which statement?", new String[] { "switch", "if-else", "if", "while" }, 'B')

public static void main(String[] args)

// Populate the quiz list.

List<OuizEntry> quiz = new ArrayList<OuizEntry>(); for (OuizEntry entry: quizEntries)

quiz.add(entry); // Perform the quiz. System.out.println("Java Ouiz");

lterator<OuizEntry> iter = quiz.iterator();

OuizEntry qe = iter.next(); System.out.println(qe.getQuestion()); String[] choices = qe.getChoices(); for (int i = 0; i < choices.length; i++)

System.out.println(" " + (char) ('A'+i) + ": " + choices[i]); int choice = -1;

while (choice < 'A' || choice > 'A'+choices.length) {

System.out.print("Enter choice letter: ");

// Remove trailing characters up to and including the newline

// to avoid having these characters automatically returned in

// subsequent System.in.read() method calls.

choice = Character.toUpperCase((char) choice);

catch (java.io.IOException ioe) {

System.out.println("You are correct!\n"); else

System.out.println("You are not correct!\n");

JavaOuiz first creates a list of quiz entries. In a more sophisticated application, I would obtain quiz data from a database and dynamically create the entries. JavaOuiz then performs the quiz with the help of iterator() and its returned Iterator instance's hasNext() and next() methods.

Listing 37 reveals the companion OuizEntry class. Listing 37. A helper class for storing a quiz's data class OuizEntry {

private String question; private String[] choices; private char answer;

OuizEntry(String question, String[] choices, char answer) {

this.question = question; this.choices = choices; this.answer = answer;

// Demonstrate returning a copy of the choices array to prevent clients // from directly manipulating (and possibly screwing up) the internal // choices array.

String[] temp = new String[choices.length]; System.arraycopy(choices, 0, temp, 0, choices.length); return temp;

String getOuestion() {

return question;

char getAnswer() {

return answer;

OuizEntry is a reusable class that stores quiz data. I did not nest OuizEntry in JavaOuiz because OuizEntry is useful for all kinds of quizzes. However, I made this class package-private by not declaring OuizEntry to be a public class because it is a helper class to a quiz's main class (such as JavaOuiz).

55. (int) (fA(f>>>32)) is used instead of (int) (fA(f>>32)) in the hash code generation algorithm because >>> always shifts a 0 to the right, which does not affect the hash code, whereas >> shifts a 0 or a 1 to the right, which affects the hash code when a 1 is shifted.

56. Listing 38 presents the FrequencyDemo application that was called for in Chapter 8.

Listing 38. Reporting the frequency of last command-line argument occurrences In the previous command-line arguments import java.util.LinkedList; import java.util.Collections; import java.util.List;

public class FrequencyDemo {

public static void main(String[] args) {

List<String> listOfArgs = new LinkedList<String>();

String lastArg = (args.length == 0) ? null : args[args.length-1];

listOfArgs.add(args[i]); System.out.println("Number of occurrences of " + lastArg + " = " + Collections.frequency(listOfArgs, lastArg));

Was this article helpful?

0 0

Post a comment