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