我使用覆盖的equals方法制作了自己的类,该方法仅检查名称(类中的属性)是否相等.现在,我将该类的某些实例存储在HashSet中,以便在HashSet中不存在具有相同名称的实例.
我的问题:如何检查HashSet是否包含此类对象. .contains()在那种情况下不起作用,因为它与.equals()方法一起工作.我想检查它是否真的是同一对象.
编辑:
package testprogram;
import java.util.HashSet;
import java.util.Set;
public class Example {
private static final Set set = new HashSet();
private final String name;
private int example;
public Example(String name, int example) {
this.name = name;
this.example = example;
set.add(this);
}
public boolean isThisInList() {
return set.contains(this);
//will return true if this is just equal to any instance in the list
//but it should not
//it should return true if the object is really in the list
}
public boolean remove() {
return set.remove(this);
}
//Override equals and hashCode
}
对不起,我的英语水平不是很好.请再次询问您是否不明白我的意思.