What is the difference between HashMap
, LinkedHashMap
and TreeMap
in Java?
I don\'t see any difference in the output as all the three
HashMap
can contain one null key.
HashMap maintains no order.
TreeMap
TreeMap can not contain any null key.
TreeMap maintains ascending order.
LinkedHashMap
LinkedHashMap can be used to maintain insertion order, on which keys are inserted into Map or it can also be used to maintain an access order, on which keys are accessed.
Examples::
1) HashMap map = new HashMap();
map.put(null, "Kamran");
map.put(2, "Ali");
map.put(5, "From");
map.put(4, "Dir");`enter code here`
map.put(3, "Lower");
for (Map.Entry m : map.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
2) TreeMap map = new TreeMap();
map.put(1, "Kamran");
map.put(2, "Ali");
map.put(5, "From");
map.put(4, "Dir");
map.put(3, "Lower");
for (Map.Entry m : map.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
3) LinkedHashMap map = new LinkedHashMap();
map.put(1, "Kamran");
map.put(2, "Ali");
map.put(5, "From");
map.put(4, "Dir");
map.put(3, "Lower");
for (Map.Entry m : map.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}