我试图减去两个自定义对象的Arraylist但是arraylist中对象的Hashcode是不同的。
List<QuizObject> list1 = new ArrayList<QuizObject>();
List<QuizObject> list2 = new ArrayList<QuizObject>();
QuizObject obj1 = new QuizObject();
QuizObject obj2 = new QuizObject();
QuizObject obj3 = new QuizObject();
obj1.setName("piyush");
obj2.setName("stuti");
obj3.setName("ayush");
list1.add(obj1);
list1.add(obj2);
list1.add(obj3);
QuizObject obj4 = new QuizObject();
QuizObject obj5 = new QuizObject();
QuizObject obj6 = new QuizObject();
obj4.setName("piyush");
obj5.setName("stuti");
obj6.setName("teri");
list2.add(obj4);
list2.add(obj5);
list2.add(obj6);
list1.removeAll(list2);
Log.d("completezz", "List 1" + list1);
Log.d("completezz", "List 2" + list2);
System.out.println("Set A : " + list1);
System.out.println("Set B : " + list2);
答案 0 :(得分:0)
在QuizObject
课程中,您需要覆盖equals
(如果您计划使用hashCode
)方法,则需要HashMap
并编写一个可以比较任何两个方法的合适逻辑QuizObject
个对象。
下面是一个可以在Java 1.7环境中使用的示例代码,但还有很多其他方法可以做到这一点。
import java.util.Objects;
public class QuizObject {
private String name;
//getters and setters
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof QuizObject)) {
return false;
}
QuizObject quizObject= (QuizObject) o;
return Objects.equals(name, quizObject.name);
}
//Override this method only if you plan to use HashMaps
//an ArrayList does not actually need to use the hashCode() method
//since the order of the elements in an ArrayList is determined by the
//order in which they were inserted
@Override
public int hashCode() {
return Objects.hash(name);
}
}
答案 1 :(得分:0)
ArrayList
不使用hashCode。它依赖于equals()
方法定义的对象相等性。您需要适当地覆盖equals()
对象,否则通过Object.equals()
和==
使用对象标识。