zoukankan      html  css  js  c++  java
  • List.removeAll()无效 解决方案

    问题:

    Tale(实体)   List1<Tale>   List2<Tale>

    list1.removeAll(list2);   list1的size没有改变

    原因:
    removeAll 的执行流程

     发现 自定义对象的equals()方法使用的是 Object的equals()方法,比较的是对象在JVM中的内存地址,而不是像String类一样只是比较值的相同(String类覆盖了equals()方法)。

    equals 方法实现的时候必须要满足的特性:

    1.(reflexive)自反性:

    对于任何非 null 的引用值 x,x.equals(x) 必须为 true;

    2.(symmetric)对称性:
    对于任何非 null 的引用值 x,y,当且仅当 y.equals(x) 返回 true 时,x.equals(y) 也要返回 true 。

    3.(transitive)传递性:
    对于任何非 null 的引用值 x,y,z, 如果 x.equals(y) 返回 true,y.equals(z) 返回 true,那么 x.equals(z) 一定要返回 true。

    4.(consistent)一致性:
    对于任何非 null 的引用值 x,y,只要 equals() 方法没有修改的前提下,多次调用 x.equals(y) 的返回结果一定是相同的。

    5.(non-nullity)非空性
    对于任何非 null 的引用值 x,x.equals(null) 必须返回 false。

    解决方案 

    使用Lombok 中 包含的注解 @EqualsAndHashCode来自动覆盖equals()和hashCode()方法。
    在 IDEA > Setting > Plugins 中搜索 lombok 下载支持插件

    使用Maven引入

    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.10</version>
        <scope>provided</scope>
    </dependency>

      我根据我的项目需求改的equals

            @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            JdzChildrenVO that = (JdzChildrenVO) o;
           if (this.getId().equals(((JdzChildrenVO) o).groupId)) return true;//这是我添加的一行代码
            return Objects.equals(id, that.id) &&
                    Objects.equals(name, that.name) &&
                    Objects.equals(level, that.level) &&
                    Objects.equals(parent, that.parent) &&
                    Objects.equals(status, that.status) &&
                    Objects.equals(groupId, that.groupId) &&
                    Objects.equals(requiredChoice, that.requiredChoice) &&
                    Objects.equals(multipleChoice, that.multipleChoice) &&
                    Objects.equals(classifyCode, that.classifyCode) &&
                    Objects.equals(unit, that.unit) &&
                    Objects.equals(displayType, that.displayType) &&
                    Objects.equals(sort, that.sort);
        }

    之后在需要覆盖重写equals()和hashCode()方法的类里 使用 @EqualsAndHashCode注解 就大功告成了

  • 相关阅读:
    snmp安装zabbix
    〖Demo〗-- 用Django实现Video页面分类查询
    〖Python〗-- Django的ORM性能优化建议
    〖Web〗-- 新特性之WebSocket
    〖Python〗-- 数据结构
    〖缓存〗-- Memcached 与 Redis
    〖算法〗-- NB二人组:堆排序、归并排序
    〖算法〗-- 快速排序 、希尔排序、计数排序
    〖算法〗-- 排序lowB三人组:冒泡排序、选择排序、 插入排序
    〖算法〗-- 递归、二分查找、列表查找
  • 原文地址:https://www.cnblogs.com/wangshuang123/p/12567570.html
Copyright © 2011-2022 走看看