HashMap, TreeMap and LinkedHashMap difference
Difference
- HashMap and LinkedHashMap contains data in key value pair. TreeMap also contains data in key value pair but it is sorted according to natural ordering (ascending order).
Map<Integer, String> codeCityHashMap = new HashMap<Integer, String>();
codeCityHashMap.put(11, "Delhi");
codeCityHashMap.put(22, "Mumbai");
codeCityHashMap.put(33, "Kolkata");
codeCityHashMap.put(44, "Chennai");
Map<Integer, String> codeCityLinkedHashMap = new LinkedHashMap<Integer, String>();
codeCityLinkedHashMap.put(11, "Delhi");
codeCityLinkedHashMap.put(22, "Mumbai");
codeCityLinkedHashMap.put(33, "Kolkata");
codeCityLinkedHashMap.put(44, "Chennai");
Map<Integer, String> codeCityTreeMap = new TreeMap<Integer, String>();
codeCityTreeMap.put(44, "Chennai");
codeCityTreeMap.put(11, "Delhi");
codeCityTreeMap.put(33, "Kolkata");
codeCityTreeMap.put(22, "Mumbai"); - If you know the key then you can get the value in HashMap, LinkedHashMap and TreeMap.
- HashMap, LinkedHashMap and TreeMap doesn't allow duplicate keys but allows duplicate values, means two different keys can have same values. But two different values can't have same key.
codeCityHashMap.put(22, "Pune");
System.out.println(codeCityHashMap);
Output: {33=Kolkata, 22=Pune, 11=Delhi, 44=Chennai}
//Mumbai is replaced with Pune for 22
codeCityLinkedHashMap.put(22, "Pune");
System.out.println(codeCityLinkedHashMap);
Output: {33=Kolkata, 22=Pune, 11=Delhi, 44=Chennai}
//Mumbai is replaced with Pune for 22
codeCityTreeMap.put(22, "Pune");
System.out.println(codeCityTreeMap);
Output: {11=Delhi, 22=Pune, 33=Kolkata, 44=Chennai}
//Mumbai is replaced with Pune for 22 - HashMap and LinkedHashMap allows only one null value as a key. TreeMap doesn't allow null value as a key. It throws NullPointerException. Though multiple keys can have null values in any of these three collections.
codeCityHashMap.put(null, "Ratlam");
codeCityHashMap.put(null, "Bangalore");
codeCityHashMap.put(55, null);
System.out.println(codeCityHashMap);
Output: {33=Kolkata, 22=Pune, 55=null, 11=Delhi, 44=Chennai, null=Bangalore} - HashMap doesn't maintain insertion order. LinkedHashMap maintains an insertion order. TreeMap maintains a natural order i.e. ascending order.
System.out.println(codeCityHashMap);
Output: {33=Kolkata, 22=Pune, 55=null, 11=Delhi, 44=Chennai, null=Bangalore}
System.out.println(codeCityLinkedHashMap);
Output: {11=Delhi, 22=Pune, 33=Kolkata, 44=Chennai, null=Bangalore}
System.out.println(codeCityTreeMap);
Output: {11=Delhi, 22=Pune, 33=Kolkata, 44=Chennai} - HashMap and LinkedHashMap implements Map interface but TreeMap implements Map, SortedMap and NavigableMap.
Comments
Post a Comment