Collections

A collection allows a group of objects to be treated as a single unit. Arbitrary objects can be stored, retrieved, and manipulated as elements of collections. The collection framework comprises three main parts:

Core Interfaces

Interface Description
Collection Basic interface that defines the operations that all classes that maintain collections of objects implement.
Set Extends the Collection interface for sets that maintain unique elements.
List Extends the Collection interface for lists that maintain their elements in a sequence, i.e. the elements are in order.
Map A basic interface that defines operations that represent mapings of keys to values.

Implementations

The java.util package provides implementations of a selection of well-known data structures, based on the core interfaces.
Data Structures Set SortedSet List Map SortedMap
Hash table HashSet HashMap Hashtable
Resizable Array ArrayList Vector
Balanced Tree TreeSet TreeMap
Linked List LinkedList

Algorithms

The class java.util.Collections provides methods that implement algorithms for various operations on collections, including sorting, searching and shuffling elements. A few of these methods are listed below:
static int binarySearch (List list, Object key)
Uses binary search to find the index of the key element in the list.

static void fill (List list, Object o)
Replaces all of the elements of the list with the specified element

static void shuffle (List list)
Randomly permutes the list, i.e. "shuffles" the elements

static void sort (List list)
Sorts the elements in the list into ascending order.

The Collection interface specifies the contract that all collections should implement. Some of the operations in the interface are optional, meaning that a collection may choose not to provide a proper implementation of such an operation.

Basic Operations are used to query a collection about its contents, add, and remove elements.

int size ();
boolean isEmpty();
boolean contains (Object element);
boolean add (Object element);		        // Optional
boolean remove (Object element);		// Optional

Bulk Operations perform a collection as a single unit.

boolean containsAll (Collection c);
boolean addAll (Collection c);		        // Optional
boolean removeAll (Collection c);		// Optional
boolean retainAll (Collection c);		// Optional
void clear ();					// Optional

Array Operations allow conversion of collections to arrays.

Object[] toArray();
Object[] toArray (Object a[]);
The first toArray() method fills an array with the elements of the collection and returns an array. The second method can be used to specify the type of array into which the elements of this collection are to be stored.

Iterators allow serial access to the elements of a collection

interface Iterator {
	boolean hasNext ();
	Object next();
	void remove(); 			// Optional
}

Given a Collection c, the following loop iterates through the elements of a collection:

Iterator iter = c.iterator();
while (iter.hasNext()) {
	Object currentElement = iter.next();
	iter.remove();
}

Sets

A Set is a collection that models a mathematical set. Duplicate elements are not allowed in the set.
Set Corresponding Mathematical Operation
a.containsAll(b) subset
a.addAll(b) union
a.removeAll(b) difference
a.retainAll(b) intersection
a.clear() empty set

The primary implementation of the Set interface is HashSet that offers near constant time performance for most operations. The sorted counterpart is TreeSet which implements the SortedSet interface and has logarithmic time complexity. A HashSet can be created based on an existing collection.

HashSet() Constructs a new empty set
HashSet (Collection c) Constructs a new set containing the elements in the specified collection without duplicates.
HashSet (int initalCapacity) Constructs a new empty set with the specfied initial capacity

Lists

Lists are collections that maintain their elements in order and can contain duplicates. In addition to operations inherited from the collection interface, the List interface also defines operations that operate specifically on lists.

Element Access by Index

Object get (int index);
Object set (int index, Object element);
void add (int index, Object element);
Object remove (int index);
boolean addAll (int index, Collection c);

In a non-empty list, the first element is at index 0 and the last element is at size()-1. The get() method returns the element at the specified index. The set() method replaces the element at the specified index with the specified element. The add() method inserts the specified element at the specified index, displacing the previous element and any other elements necessary one position towards the end of the list. The method add (Object obj) will append the specified element to the end of the list. The remove() method deletes and returns the element at the specified index, contracting the list accordingly. The addAll() method inserts the elements from the specified collection at the specified index using the specified collection's iterator.

Element Search

int indexOf (Object o);
int lastIndexOf (Object o);
These methods respectively return the index of the first and the last occurrence of the element in the list if the element is found, otherwise the value -1 is returned,

List Iterators

ListIterator listIterator();
ListIterator listIterator (int index);
The iterator from the first method returns the elements consecutively, starting with the first element, whereas the iterator from the second method starts iterating from the element indicated by the index. When traversing lists, it can be helpful to imagine a cursor between the elements, which moves forwards or backwards, depending on the call to the next() or previous() method respectively.

Three implementations of the List interface are provided in the java.util package - ArrayList, Vector, and Linked List. All three classes provide a standard constructor which creates a new empty list and a constructor which creates a list based on an existing collection. The ArrayList and the Vector classes also allow creating a new empty list with an initial capacity. The Vector and ArrayList classes implement dynamically resizable arrays. The Vector class is thread safe but the ArrayList class offers slightly better performance. When frequent insertions and deletions occur inside a list, a LinkedList can be worth considering.

Maps

A Map defines mappings from keys to values. A map does not allow duplicate keys, in other words the keys are unique, and each key maps to at most one value, implementing what are called single-valued maps. A map does not extend the Collection interface. However, the mappings can be viewed as a collection in various ways: set.

Basic Operations - these are the basic functionalities provided by the map.

Object put (Object key, Object value);
Object get (Object key);
Object remove (Object key);
boolean containsKey (Object key);
boolean containsValue (Object value);
int size();
boolean isEmpty();

The put() method inserts a mapping, i.e. a pair, also called an entry. The get() method returns the value to which the specified key is mapped, or null if no mapping is found. The remove() method deletes the entry for the specified key. The containsKey() method returns true if the specified key is mapped to a value in the map. The containsValue() returns true if there exists one or more keys that are mapped to the specified value. The methods size() and isEmpty() return the number of entries and whether the map is empty or not, respectively.

Bulk Operations

void putAll (Map t);
void clear();
The first method copies all entries from the specified map and the second method deletes all entries from a map.

There are two implementations of the Map interface in the java.util package - HashMap and Hashtable. The HashMap class provides the primary implementation of the Map interface. As was the case with collections, implementation classes provide a standard constructor, which creates a new empty map, and a constructor, which creates a new map, based on an existing one. While the HashMap class is not thread safe, the Hashtable class is.

Sets and maps have special interfaces called SortedSet and SortedMap for implementations that sort their elements in a specific order.