Friday, February 14, 2014

What is difference between HashMap, TreeMap and LinkedHashMap ?

Difference is in how the elements are ordered
  1. HashMap : Does not guarantee order, the order depends on how the elements get hashed and which bucket they land in
  2. TreeMap : TreeMap will order elements in the natural order, it will maintain Map in sorted order
  3. LinkedHashMap: Maintains elements in order of insertion
Take a look at this small program that inserts same elements in different Map objects and then prints them in order

package com.test;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class TestMap {

 public static void main(String[] args) {
  System.out.println("*****HashMap******* ");
  printMap(new HashMap(5));
  
  System.out.println("*****TreeMap******* ");
  printMap(new TreeMap());
  System.out.println("*****LinkedHashMap******* ");
  printMap(new LinkedHashMap());

 }
 private static void printMap(Map map){
  map.put(32, "Three");
  map.put(11, "One");
  map.put(25, "Two");
  map.put(53, "Five");
  map.put(44, "Four");
  for(Map.Entry entry: map.entrySet())
   System.out.println(entry);
 }
}
This is the output

*****HashMap******* 
25=Two
32=Three
11=One
44=Four
53=Five
*****TreeMap******* 
11=One
25=Two
32=Three
44=Four
53=Five
*****LinkedHashMap******* 
32=Three
11=One
25=Two
53=Five
44=Four

No comments:

Post a Comment