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 ?
- There is no hashcode method so there is no way for the JVM to see if objects m1 and m2 contain different values
- 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.
When the
hashCode()andequals(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.