Java300集零基础适合初学者视频教程
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class R {
private int count;
public R(int count) {
this.count = count;
}
@Override
public String toString() {
return "R{" + "count=" + count + " # hashCode=" + this.hashCode() + '}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
R r = (R) o;
return count == r.count;
}
// @Override
// public int hashCode() {
// return Objects.hash(count);
// }
public static void main(String[] args) {
Set set = new HashSet();
set.add(new R(5));
set.add(new R(-3));
set.add(new R(9));
set.add(new R(-2));
System.out.println(set.contains(new R(-3)));
System.out.println(set);
}
}
上面注释了hashCode方法,所以你将会看到下面的结果。
false
[R{count=9 # hashCode=2003749087}, R{count=5 # hashCode=1283928880}, R{count=-3 # hashCode=295530567}, R{count=-2 # hashCode=1324119927}]
取消注释,则结果就正确了
true
[R{count=5 # hashCode=36}, R{count=9 # hashCode=40}, R{count=-3 # hashCode=28}, R{count=-2 # hashCode=29}]



