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 ?
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 .
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.
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.
Technically, yes, you can only implement equals() method without implementing hashcode() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With