Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

java - Objects as Map keys without Hashcode and equals

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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...