javahashmapequalshashcodehash-collision

HashMap Key and Values, does i need to define equals and hashCode() all time?


I have a question about HashMap<Key,Values>.

Let's imagine this scenario:

I have a Person class:

 Person a=new Person(int id, String fullName, int age)

I didn't define the equals and hashCode on this class.

Let's suppose I want to store 10 Person in a HashMap defined as:

 Map<Integer,Person> hashMap=new HashMap<Integer,Person>();

So I will take the number of the persons from the database and then I do a for loop:

 String name="test"; int age="20";

 for(int i=size;i<size+10;i++)
 {
      hashMap.put(Integer.valuesOf(i), new Person(i,name+"i",age++));
 }

The hashMap I think will use hashCode() of the Integer class and I will get a unique hash which will be stored in the hashMap along with the Person objects. If I'm sure that this hash will be unique I don't need to define the hashCode and equals on the object, no? or at least I need just to define the equals in order to compare between two person in the future.

Am I wrong?


Solution

  • The key of a HashMap needs to implement consistent hashCode and equals. Note that a hashCode does not have to be unique, but the closer it is to it, the better performance you'll get. java.lang.Integer already implements both of these.

    The value of a HashMap doesn't have to implement anything, although having an equals method will help if you want to use containsValue.