While you can always look in the API under java.util (which is always a great idea), the following tables will help give you a concise reference of what is available and what each is used for.
Table 11.2 overviews the List , Map , and Set interfaces. It shows you what they are used for, what classes in the API implement them, and how long they've been in the language.
Interface | Purpose |
---|---|
List |
|
Map |
|
Set |
|
These interfaces, as we can see from the number of classes implementing each, are the parents of many related collections. So now that we have a sense of the collections landscape, let's look at some of the original collections in greater detail.
The fundamental interface from which these derive is the Collection interface. Its methods were outlined above. Once you have created a collection of a certain type, then you can add objects to it using the add() method. Note that add() returns a boolean specifying whether the collection item was added. If the item is a duplicate, it will not be added to the collection and will return false .
You can loop over the collection to read, write, or modify each element one by one using an Iterator or an Enumeration .
A class implementing the Iterator interface can step through a collection item by item. The Iterator was introduced in Java 1.2 to replace the Enumeration . There are two chief ways in which an Iterator improves upon the Enumeration :
The caller can remove elements from the collection in a clear, well-defined manner. This was not easily possible with Enumeration .
Method names have been improved.
Preferring Iterator to Enumeration is recommended. The methods of an Iterator are as follows :
hasNext() returns true if the Iterator has more elements
next () returns the next element in the iteration
remove() removes the last element the Iterator returned
You can call an iterator's next() method to look up the elements in the collection one by one. Use caution when employing the remove() method, because it will remove the element that the last call to next() returned. So, you must call next() and only then call remove() .
java.util.AbstractCollection is an abstract class. It was added in JDK 1.2 to aid developers implementing the Collection interface. Recall that interfaces can contain no method implementations ; they just define what must be implemented. This meant that developers had to redefine certain useful methods over and over again. This was a lot of work for little return.
So the makers of the JDK created AbstractCollection as a partial implementation. It is an abstract class and as such it contains implementations for routine methods, but leaves the core methods abstract for you. Because the class is abstract, you can override the implementations it provides if you have a specialized need, but otherwise you aren't forced to do all of that work. The advantage to this choice is that it achieves an excellent balance of power, flexibility, and efficiency.
Top |