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注解 就大功告成了

  • 相关阅读:
    21. Merge Two Sorted Lists
    496. Next Greater Element I
    (转载)深度学习的weight initialization
    Python collections模块
    Iterables vs. Iterators vs. Generators
    (转)iPhone开发关于UDID和UUID的一些理解
    uniqueIdentifier在ios7不支持后的替代方法
    Android——列表视图 ListView(一)Arrayadapter
    Android——对话框2(日期和时间对话框)
    Android——子线程操作主线程
  • 原文地址:https://www.cnblogs.com/wangshuang123/p/12567570.html
Copyright © 2011-2022 走看看