java中Arraylist的retainall()和removeAll()方法是对象的Hash代码还是对象的值

时间:2016-09-26 05:22:43

标签: java list arraylist collections

我试图减去两个自定义对象的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);

2 个答案:

答案 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()==使用对象标识。