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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…