Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
146 LESSON 14 INTRODUCTION TO COLLECTIONS LISTING 14-2 (continued) // element of this collection for (int i=0; i<totalElem;i++){ Object currElement = customers.get(i); if (currElement instanceof Customer){ Customer currentCust= (Customer)customers.get(i); currentCust.doSomething(); } else if (currElement instanceof Order){ Order currentOrder = (Order) customers.get(i); currentOrder.doSomething(); } } COLLECTION INTERFACES FROM JAVA.UTIL A typical collection class implements several interfaces, which represent a well-designed hierarchy. For example, ArrayList implements the List interface, which extends Collection . Just reading the com- ments in the source code for java.util habitats can give you a good idea of what they are for. Collection extends Iterable ; there are no classes that directly implement this interface. Only its descendent interfaces are implemented. You can use a for-each loop (see the "Arrays Revisited" section earlier in this lesson) with classes that implement Iterable . The List interface is defi ned for the ordered collections: ArrayList , Vector , and LinkedList . It allows duplicate elements. For example, the following code snippet will create two elements in ArrayList : myArrayList.add("Mary"); myArrayList.add("Mary"); The Set interface is implemented by collections that don't allow duplicate elements, e.g., HashSet and SortedSet . For example, the following code snippet will create one element in HashSet . The second line will fi nd out that Mary already exists, and won't change it and will return false : myHashSet.add("Mary"); myHashSet.add("Mary"); The Map interface is for storing key/value pairs. A map can't contain duplicate keys and each key can be mapped to only one value (object). You'll see some relevant code examples in the next section. The Queue interface is mainly for collections that require fi rst-in-fi rst-out (FIFO) operation (so- called priority queues are the exception). Every new element is added to the tail of the queue and the elements are retrieved from the head of the queue. You can restrict the size of the queue if need be. LinkedList is one of the classes that implement the Queue interface. Now let's look at some of the classes that implement these interfaces.