我有一个名为Record
的对象类,其中包含一个Data
类对象的矢量
对象类Data
除了两个变量外什么都没有
Object value;
String name;
我在
Record
类中重写equals方法,如下所示:public boolean equals(Object obj) {
boolean check = true;
for(int i=0; i<this.coloumnsOfData.size();i++) {
System.out.println( ((Record) obj).coloumnsOfData.get(i).name + " OBJECT " + ((Record) obj).coloumnsOfData.get(i).value );
System.out.println( coloumnsOfData.get(i).name + " THIS " + coloumnsOfData.get(i).value );
if( !((((Record) obj).coloumnsOfData.get(i).name).equals(this.coloumnsOfData.get(i).name)) || !((((Record) obj).coloumnsOfData.get(i).value).equals(this.coloumnsOfData.get(i).value))) {
check=false;
}
}
return (obj instanceof Record && check);
}
我将HashSet初始化如下:
Set<Record> answer= new HashSet<Record>()
并开始测试
Record r1 = new Record();
r1.coloumnsOfData.add(new Data(new Double( 1.5 ),"gpa"));
r1.coloumnsOfData.add(new Data(new String("John"),"name"));
r1.coloumnsOfData.add(new Data(new Integer( 2 ),"id"));
Record r2 = new Record();
r2.coloumnsOfData.add(new Data(new Double( 1.5 ),"gpa"));
r2.coloumnsOfData.add(new Data(new String("John"),"name"));
r2.coloumnsOfData.add(new Data(new Integer( 2 ),"id"));
System.out.println(r1.equals(r2)); //RETURNS TRUE
answer.add(r1);
System.out.println(answer.contains(r2)); //RETURNS FALSE
任何帮助了解问题所在的帮助将不胜感激。
最佳答案
尝试也重写hashCode方法。它应该工作。
您可以在此处找到说明:
HashSet contains() method