【发布时间】:2017-04-27 16:48:18
【问题描述】:
我有以下代码:
public class Trooper {
private String name;
private boolean mustached;
public Trooper(String name, boolean hasMustache) {
this.name = name; this.mustached = hasMustache;
}
public String getName() { return name; }
public boolean hasMustache() { return mustached; }
public boolean equals(Trooper other) {
if (this == other) return true;
if (null == other || !(other instanceof Trooper)) return false;
Trooper that = (Trooper) other;
return this.name.equals(that.name) && this.mustached == that.mustached;
}
public int hashCode() { return 1; }
}
然后运行如下:
ArrayList<Trooper> troopers = new ArrayList<>();
troopers.add(new Trooper("Farva", true));
troopers.add(new Trooper("Farva", true));
troopers.add(new Trooper("Rabbit", false));
troopers.add(new Trooper("Mac", true));
Set<Trooper> trooperSet = new HashSet<>(troopers);
为什么下面的代码返回false?
trooperSet.contains(new Trooper("Mac", true));
我了解在调用 contains 方法时如何在 hashSet 中使用 hashCode 和 equals。我能猜到它返回 false 而不是 true 的唯一原因是 equals 方法没有被正确覆盖。如果这是上一条语句返回 false 的原因,为什么会这样?
【问题讨论】:
标签: java overriding equals hashcode hashset