天天看点

两个List集合使用removeAll()方法遇到的坑,无法移除掉两个集合相同的数据。

1楼主在对比两个集合时,使用removeAll()方法无法删除掉它们相同的部分,之后写了一个demo测验一下removeAll()。

//测试包含基本数据类型String的两个list集合使用removeALL() 方法
 public static void main(String[] args) {
    List <String> stringList1 = new ArrayList <String>();
    for(int i=0;i<3;i++){
        stringList1.add(String.valueOf(i));
    }
    List <String> stringList2 = new ArrayList <String>();
    for(int i=0;i<3;i++){
        stringList2.add(String.valueOf(i+1));
    }
    stringList1.removeAll(stringList2);
    for(int i=0;i<stringList1.size();i++){
        System.out.println(stringList1.get(i));
    }
  }
           

输出结果为0,可见基本数据类型可以正常使用removeAll()方法

两个List集合使用removeAll()方法遇到的坑,无法移除掉两个集合相同的数据。

2下面测试一下包含对象的两个list集合使用removeAll()方法结果

//student实体类
public class Student implements Serializable {

  private static final long serialVersionUID = 7766151923728207061L;

  private int studentno;
  private String name;

  public int getStudentno() {
      return studentno;
  }
  public void setStudentno(int studentno) {
      this.studentno = studentno;
  }
  public String getName() {
      return name;
  }
  public void setName(String name) {
      this.name = name;
  }
}

//测试removeAll()方法
public static void main(String[] args) {
    List <Student> stringList3 = new ArrayList <Student>();
    for(int i=0;i<3;i++){
        Student student = new Student();
        student.setStudentno(i);
        student.setName(String.valueOf(i));
        stringList3.add(student);
    }
    List <Student> stringList4 = new ArrayList <Student>();
    for(int i=0;i<3;i++){
        Student student = new Student();
        student.setStudentno(i+1);
        student.setName(String.valueOf(i+1));
        stringList4.add(student);
    }
    stringList3.removeAll(stringList4);
    for(int i=0;i<stringList3.size();i++){
        System.out.println(stringList3.get(i).getStudentno()+":"+stringList3.get(i).getName());
    }
  }

           

输出结果,应该输出0:0和3:3,结果表明removeAll()方法没有达到效果

两个List集合使用removeAll()方法遇到的坑,无法移除掉两个集合相同的数据。

3原因是因为在调用removeAll()方法时会调用equals()方法比较两个对象是否相等,student类默认继承Object类的equais()方法,Object类的equals方法会先比较两个对象student的地址是否相同,很显然,每个对象的地址是不相同的,所以removeAll()方法认为两个对象不相同并没有起到移除作用。

4解决办法,重写equals()方法。比较两个学生对象,比较他们的学号,如下:

@Override
  public boolean equals(Object obj) {
      if (this.getStudentno() == ((Student) obj).getStudentno()) {
          return true;
      }
      return false;
  }