Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects as Map keys without Hashcode and equals

Tags:

java

public class Contact
{
    int i;
    String name;
    public Contact(int iVal, String nameVal)
    {
        i = iVal;
        name = nameVal;
    }
}   

public class MultiMap
{
    public static void main (String args[])
    {
        java.util.HashMap m = new java.util.HashMap();
                Contact m1 = new Contact(1, "name");
        Contact m2 = new Contact(1, "name");
        m.put(m1, "first");
        m.put(m2, "second");
        System.out.println(m.get(m1));
        System.out.println(m.get(m2));
    }
}   

Output is:

first 
second 

How does this "get" method behave ? As both m1 and M2 have same values and I have not overridden hashcode(), will Object class's equals() method be called ?

Is this correct ?

  1. There is no hashcode method so there is no way for the JVM to see if objects m1 and m2 contain different values
  2. There is no equals method overridden so Object class's equals() is invoked and as both objects are different the code above works fine without m2 replacing m1's value.
like image 878
Ved Avatar asked Jul 29 '11 10:07

Ved


People also ask

Can we have object as key in Map?

A simple thumb rule is to use immutable objects as keys in a HashMap . because: If it were mutable, then the hashcode() value or equals() condition might change, and you would never be able to retrieve the key from your HashMap .

What happens if we do not override hashCode and equals () in HashMap?

If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.

Can we make object as a key in HashMap?

If you want to make a mutable object as a key in the hashmap, then you have to make sure that the state change for the key object does not change the hashcode of the object. This can be done by overriding the hashCode() method. But, you must make sure you are honoring the contract with equals() also.

Can we have equals without hashCode?

Technically, yes, you can only implement equals() method without implementing hashcode() method.


1 Answers

When the hashCode() and equals(Object o) methods are not overridden by your class, Java just uses the actual reference to the object in memory to calculate the values (ie. check if it is the same instantiation of the class). That is why you still get both results.

like image 145
Nico Huysamen Avatar answered Sep 23 '22 01:09

Nico Huysamen