List
A List is a data structure that holds an indexed collection. The ArrayList
class uses an object array to hold its values. The values are copied into a larger
array
if the capacity is exceeded, but this can be avoided by specifying an initial
capacity in the constructor. ArrayList is not thread-safe,
but CopyOnWriteArrayList is a thread-safe alternative.
The LinkedList class uses a chain of Node objects to create a dynamically-
sized list. A node contains a value along with a reference to the previous node
and the next node in the chain. This allows nodes
to be inserted or removed
without reorganizing the list, but it requires iterating through the list to access
an element by its index. LinkedList is not thread-safe, but it can be decorated
by the Collections#synchronizedList() method.
Map
A Map is a data structure that associates keys with values.
The HashMap class
uses an array of linked lists to store Entry objects. An entry contains a key,
a value, and a reference to the next entry in the chain. When you put a key/value
pair in the map, a mathematical function such as the modulo operator (%)
constrains the key’s hash code to an index in the array. Unique keys that map
to the same index are linked together, but duplicate
keys will overwrite the
existing entries. When you look up a value by key, the index is computed again
and every entry in the linked list is inspected until a matching key is found.
HashMap
requires that keys implement the hashCode() and equals()
methods correctly. If the hash code is not unique, performance of the map will
suffer because the linked lists will grow disproportionately.
If the hash code
is not consistent, entries can get lost in the map and leak memory.
If the size of a HashMap exceeds 75% of its capacity, the array is doubled and
all of the entries are rehashed. This can be avoided by specifying an initial
capacity and its load factor in the constructor. HashMap
does not maintain the
insertion order of its entries, but LinkedHashMap provides that functionality
by storing its entries in an auxiliary LinkedList. HashMap is not thread-safe,
but ConcurrentHashMap is a thread-safe alternative.
Deque
A Deque (double-ended queue) is a data structure that can insert or retrieve
values from two sides. A deque
that removes elements in a last-in-first-out
(LIFO) policy is called a stack. A deque that removes elements in a
first-in-first-
out (FIFO) policy is called a queue. The ArrayDeque class uses an object
array to store its values. ArrayDeque can be used as a stack or a queue,
and generally outperforms the Stack and LinkedList classes for the same
purpose.
ArrayDeque is not thread-safe, but ConcurrentLinkedDeque
is a thread-safe alternative.