【发布时间】:2011-08-09 05:55:54
【问题描述】:
这是 java main() 方法:
public static void main(String[] args) {
HashSet set = new HashSet();
Mapper test = new Mapper("asd", 0);
set.add(test);
System.out.println(new Mapper("asd", 0).equals(test));
System.out.println(set.contains(new Mapper("asd", 0)));
}
我的 Mapper 类是:
class Mapper {
String word;
Integer counter;
Mapper (String word, Integer counter) {
this.word = word;
this.counter = counter;
}
public boolean equals(Object o) {
if ((o instanceof Mapper) && (((Mapper)o).word == this.word)) {
return true;
}
return false;
}
}
结果是:
是的
假
根据 HashSet 规范,在这个方法中我读到:“如果这个集合包含指定的元素,则返回 true。更正式地说,当且仅当这个集合包含一个元素 e 时才返回 true (o==null ? e= =null : o.equals(e))。"
那么,谁能解释我哪里错了?还是……?
谢谢。
【问题讨论】:
-
只是为了添加一些东西,如果你想比较它的值,你应该使用 String
equals()方法(而不是==,这是参考测试)。