从对象列表中删除重复项而不依赖于集合
在java中,这里有一个问题。对象已经编译,因此 hash() 和 equals() 方法不能被覆盖。将其放入集合中,然后放回到列表中是行不通的,因为当前在 equals() 中尚未定义唯一性标准,并且无法覆盖它。
In java, and there is one catch here. The objects are already compiled and the hash() and equals() methods therefore cannot be over written. Throwing it into a set, then back into a list will not work because the criteria for uniqueness isn't currently defined in equals() and this cannot be overridden.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您仍然应该能够创建子类并创建有效的
equals
和hashcode
方法,除非类/方法是final
。如果是这种情况,您可以使用组合,基本上为要放入集合中的内容创建一个包装器,并让包装器的
equals
和hashcode
正确实现合约,对于被包裹的东西。你的处境很艰难,因为我读到的是原始类没有遵循 equals 和 hashcode 的约定,这在 Java 中是一个真正的问题。这是一个相当严重的错误。
You should still be able to create subclasses and create
equals
andhashcode
methods that work, unless the classes/methods arefinal
.If that is the case, you could use composition, basically create a wrapper for the things you are putting in the collection, and have the wrapper's
equals
andhashcode
implement the contract correctly, for the thing being wrapped.You are in a tough position, because what I am reading is that the original classes are not following the contract for
equals
andhashcode
which is a real problem in Java. It's a pretty serious bug.为您的对象编写一个自定义 Comparator 并使用Collections.sort() 对列表进行排序。然后通过循环遍历列表来删除重复项。
Write a custom Comparator for your objects and use Collections.sort() to sort your list. And then remove duplicates by going though a list in a loop.
compareTo
方法将返回-1
、0
、1
;如果0
,则从列表中删除。a
compareTo
method would return-1
,0
,1
; if0
, remove from list.