The collections framework in
java.util provides a number of generic classes for sets of data with functionality that can't be provided by regular arrays.
Collections framework contains interfaces for
Collection<O>, with main sub-interfaces
Set<O>, and mapping collection
Map<K,V>. Collections are the root interface and are being implemented by many other collection frameworks.
Collections are objects that can store collections of other objects inside of them. You can specify the type of data stored in a collection using Generics.
Collections generally use the
Java 1.4.2 and below do not support generics. As such, you can not specify the type parameters that a collection contains. In addition to not having type safety, you must also use casts to get the correct type back from a collection.
In addition to
Collection<E>, there are multiple major types of collections, some of which have subtypes.
List<E>is an ordered collection of objects. It is similar to an array, but does not define a size limit. Implementations will usually grow in size internally to accomodate new elements.
Set<E>is a collection of objects that does not allow duplicates.
Set<E>that also specifies element ordering.
Map<K,V>is a collection of key/value pairs.
Map<K,V>that also specifies element ordering.
Java 5 adds in a new collection type:
Queue<E>is a collection of elements meant to be processed in a specific order. The implementation specifies whether this is FIFO or LIFO. This obsoletes the
Java 6 adds in some new subtypes of collections.
Set<E>with special navigation methods built in.
Map<K,V>with special navigation methods built in.
Queue<E>that can be read from either end.
Note that the above items are all interfaces. In order to use them, you must find the appropriate implementing classes, such as
Each type of collection has multiple implementations that have different performance metrics and use cases.
Note that the Liskov Substitution Principle applies to the collection subtypes. That is, a
SortedSet<E> can be passed to a function expecting a
Set<E>. It is also useful to read about Bounded Parameters in the Generics section for more information on how to use collections with class inheritance.
If you want to create your own collections, it may be easier to inherit one of the abstract classes (such as
AbstractList) instead of implementing the interface.
Prior to 1.2, you had to use the following classes/interfaces instead:
Map. Note that Dictionary is also an abstract class rather than an interface.
These classes are obsolete and should not be used in modern code.