問題描述
我有一個名為 FormObject 的對象,它包含兩個 ArrayList - oldBooks 和 newBooks - 兩者都包含 Book 對象.
I have an object called FormObject that contains two ArrayLists - oldBooks and newBooks - both of which contain Book objects.
oldBooks 允許包含重復的 Book 對象newBooks 不允許在其內部包含重復的 Book 對象,并且不能在 oldBooks 列表中包含任何重復的 Book 對象.
oldBooks is allowed to contain duplicate Book objects newBooks is not allowed to contain duplicate Book objects within itself and cannot include any duplicates of Book objects in the oldBooks list.
重復 Book 的定義很復雜,我無法覆蓋 equals 方法,因為該定義在 Book 對象的所有用途中并不通用.
The definition of a duplicate Book is complex and I can't override the equals method as the definition is not universal across all uses of the Book object.
我計劃在 FormObject 類上有一個名為 removeDuplicateNewBooks 的方法,它將執行上述功能.
I plan to have a method on the FormObject class called removeDuplicateNewBooks which will perform the above functionality.
您將如何實施?我的第一個想法是使用 HashSets 來消除重復項,但無法覆蓋 Book 對象上的 equals 意味著它不起作用.
How would you go about implementing this? My first thought was to use HashSets to eliminate the duplicates but not being able to override equals on the Book object means it won't work.
推薦答案
您可以使用 TreeSet
與自定義 Comparator
:
- 使用
Comparator
構建TreeSet
,實現您想要的自定義邏輯 - 使用
set.addAll(bookList)
- construct the
TreeSet
with aComparator
implementing the custom logic you want - use
set.addAll(bookList)
現在 Set
只包含獨特的書籍.
Now the Set
contains only unique books.
這篇關于比較兩個列表并從中刪除重復項的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!