CS 4773 Object Oriented Systems Java Collections
Topics:
- Collection and Iterator Interface
- Concrete Collections
Collection Interface
The most important methods in the interface are as follows:
boolean add(E o);
returns true if the collection changed, false if not.
some collections do not allow duplicates.
may throw an exception if object cannot be added.
int size();
Object[] toArray();
Iterator iterator();
Returns an iterator for this collection.
An Iterator has the following main methods:
- boolean hasNext();
- Object next();
- void remove();
removes from the collection, the last element gotten by next().
Some of the methods are optional and can throw an exception if
not allowed for a particular type of collection.
The collections in Java 5 are all generic, meaning you can specify the type of
the objects in the collection.
Look at the full Collection interface in the Java documentation.
Some Concrete Collections
See Core Java Volume 2, chapter 2 for a complete list.
- ArrayList - we have used this one before
- LinkedList - An ordered sequence that allows efficient insertions and
deletions at any location.
- Supports a ListIterator that has hasPrevious and
previous as well as hasNext and next.
- The ListIterator maintains an index and can be moved in either
direction.
- See the ListIterator interface in the Java documentation
- HashSet - an unordered collection
If the HashSet is modified while using an iterator (other than with the
iterator remove method) the iteration will fail.
- TreeSet - and ordered collection
Items can be entered in any order, but the iterator returns them
in order.
It uses the natural order of the elements.
It assumes that the elements added implement Comparable and
so have a compareTo method.
- PriorityQueue = provides efficient removal of the smallest element.
Has a remove() that removes the smallest element.
An iterator does not have to traverse the collection in order.