【发布时间】:2015-10-06 20:40:34
【问题描述】:
我执行了下面的代码,发现输出是false。
import java.util.Set;
import java.util.HashSet;
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<Name> s = new HashSet<Name>();
s.add(new Name("Donald", "Duck"));
System.out.println(s.contains(new Name("Donald", "Duck")));
}
}
我想知道它的行为方式以及为什么输出是false。
【问题讨论】:
-
你还没有覆盖
hashCode。
标签: java collections set contains hashset