String, Integer, Long, Double, Float, Short and any other wrapper class should be preferred to use a key in HashMap in java


we should prefer String, Integer, Long, Double, Float, Short and any other wrapper class. Reason behind using them as a key is that they override equals() and hashCode() method, we need not to write any explicit code for overriding equals() and hashCode() method.

Let’s use Integer class as key in HashMap.


import java.util.HashMap;
import java.util.Map;

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

public class StringInMap {
   public static void main(String...a){
         
         //HashMap's key=Integer class  (Integer’s api has already overridden hashCode() and equals() method for us )
          Map<Integer, String> hm=new HashMap<Integer, String>();
          hm.put(1, "data");
          hm.put(1, "data OVERRIDDEN");
         
          System.out.println(hm.get(1));
         
   }
}
/*OUTPUT
data OVERRIDDEN
*/
If, we note above program, what we will see is we didn’t override equals() and hashCode() method, but still we were able to store data in HashMap, override data and retrieve data using get method.


>Let’s check in Integer’s API, how Integer class has overridden equals() and hashCode() method :  

public int hashCode() {
       return value;
}
public boolean equals(Object obj) {
       if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
       }
       return false;
}




Related >


Labels: Core Java
eEdit
Must read for you :