What is the difference between HashMap
, LinkedHashMap
and TreeMap
in Java?
I don\'t see any difference in the output as all the three
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.
Imagine you passed an empty TreeMap, HashMap, and LinkedHashMap into the following function:
void insertAndPrint(AbstractMap 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}