java -list集合 removeAll 移除 对象 -重写实体equals方法

前提:

在项目中需要实现一个活动未参与人名单的筛选,一开始使用的list的泛型是String 可以把参与人员在全体的list集合中筛选出来。由于后期需要筛选多个字段,所以把list集合泛型换成了实体所以就无法进行筛选。

原因

removeAll方法,是遍历调用remove方法进行删除的。在删除之前,判断了此集合元素里的内容是否包含在全部人员列表的队列中

removeAll源码

 public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        boolean modified = false;
        Iterator<?> it = iterator();
        while (it.hasNext()) {
            if (c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
    }

自己的实现方式

  //遍历参与人员名单,从全部人名单中去除
            for (StudentModel object : objects) {
                for (StudentModel studentModel : allUserName) {
                    if(studentModel.getPersonName().equals(object.getPersonName())){
                        allUserName.remove(studentModel);
                        break;
                    }
                }
            }

可以明显看出来自己写的使用了循环嵌套,效率上肯定不如removeAll的迭代器 while 单层循环的效率高

解放方案:

重写实体类的equals 方法

    private String personID;
    private String personName;
    private Integer id;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StudentModel that = (StudentModel) o;
        return   Objects.equals(personName, that.personName);
    }

注意事项
重写equals方法的时候,根据实际使用的实体字段去重写equals方法
里的对比字段
此处是坑
我这次就是实体里有两个字段,但是只有一个字段里有值。所以直接默认重写equals方法不修改是无法移除的
如下
默认重写equals

  @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StudentModel that = (StudentModel) o;
        return Objects.equals(personID, that.personID) && Objects.equals(personName, that.personName);
    }

根据实际情况重写equals

  @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StudentModel that = (StudentModel) o;
        return  Objects.equals(personName, that.personName);
    }

比如我这个有两个字段,但是只有一个字段有值。所以equals里值对比一下一个pseronName

posted @ 2021-10-12 22:12  康世行  阅读(2314)  评论(0编辑  收藏  举报