我通常不用Java编写代码,但最近我开始没有选择.我可能对如何正确使用HashSet有一些重大误解.所以我可能做的事情可能是完全错误的.但是我很感激您提供的任何帮助.那么实际问题:
在我写的一个小程序中,我生成了非常相似的对象,这些对象在创建时会有一个非常具体的id(a string或在我的上一次迭代中long).因为每个对象都会产生新对象,所以我想过滤掉我已创建的所有对象.所以我开始将每个新对象的id抛入我的Hash(Set)并测试HashSet.contains(),如果之前创建了一个对象.这是完整的代码:
// hashtest.java
import java.util.HashSet;
class L {
public long l;
public L(long l) {
this.l = l;
}
public int hashCode() {
return (int)this.l;
}
public boolean equals(L other) {
return (int)this.l == (int)other.l;
}
}
class hashtest {
public static void main(String args[]) {
HashSet<L> hash = new HashSet<L>();
L a = new L(2);
L b = new L(2);
hash.add(a);
System.out.println(hash.contains(a));
System.out.println(hash.contains(b));
System.out.println(a.equals(b));
System.out.println(a.hashCode() == b.hashCode());
}
}
Run Code Online (Sandbox Code Playgroud)
产生以下输出:
true
false …Run Code Online (Sandbox Code Playgroud)