All offer a key->value map and a way to iterate through the keys. The most important distinction between these classes are the time guarantees and the ordering of the keys.
- HashMap offers 0(1) lookup and insertion. If you iterate through the keys, though, the ordering of the keys is essentially arbitrary. It is implemented by an array of linked lists.
- TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you need to iterate through the keys in sorted order, you can. This means that keys must implement the Comparable interface.TreeMap is implemented by a Red-Black Tree.
- LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by their insertion order. It is implemented by doubly-linked buckets.
Imagine you passed an empty TreeMap, HashMap, and LinkedHashMap into the following function:
void insertAndPrint(AbstractMap<Integer, String> map) {
int[] array= {1, -1, 0};
for (int x : array) {
map.put(x, Integer.toString(x));
}
for (int k: map.keySet()) {
System.out.print(k + ", ");
}
}
The output for each will look like the results below.
For HashMap, the output was, in my own tests, { 0, 1, -1}, but it could be any ordering. There is no guarantee on the
ordering.
Treemap,the output was,{ -1, 0, 1}
LinkedList,the output was,{ 1, -1, 0}