Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - Why we need to override hashCode and equals?

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...