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

Categories

By default hashCode and equals works fine. I have used objects with hash tables like HashMap, without overriding this methods, and it was fine. For example:

public class Main{
public static void main(String[] args) throws Exception{
    Map map = new HashMap<>();
    Object key = new Main();
    map.put(key, "2");
    Object key2 = new Main();
    map.put(key2, "3");
    System.out.println(map.get(key));
    System.out.println(map.get(key2));
}
}

This code works fine. By default hashCode returning memory address of object, and equals checks if two objects is the same. So what is the problem with using default implementation of this methods?

See Question&Answers more detail:os

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

1 Answer

Note this example from an old pdf I have:

This code

    public class Name {

private String first, last;

public Name(String first, String last) { this.first = first; this.last = last;

}

public boolean equals(Object o) {

if (!(o instanceof Name)) return false;

Name n = (Name)o;

return n.first.equals(first) && n.last.equals(last);

}

public static void main(String[] args) {

Set s = new HashSet();

s.add(new Name("Donald", "Duck"));

System.out.println(

s.contains(new Name("Donald", "Duck")));

}

}

...will not always give the same result because as it is stated in the pdf

Donald is in the set, but the set can’t find him. The Name class violates the hashCode contract

Because, in this case, there are two strings composing the object the hashcode should also be composed of those two elements.

To fix this code we should add a hashCode method:

public int hashCode() { 
return 31 * first.hashCode() + last.hashCode();
}

This question in the pdf ends saying that we should

override hashCode when overriding equals


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...