Java - 使对象集合友好
如果一个对象拥有唯一的主键,那么它需要实现哪些接口才能对集合友好,特别是在高效可排序、可散列等方面?
如果主键是字符串,这些接口如何最好地实现?
谢谢!
If an object holds a unique primary key, what interfaces does it need to implement in order to be collection friendly especially in terms of being efficiently sortable, hashable, etc...?
If the primary key is a string, how are these interfaces best implemented?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须重写
Object.equals()
和Object.hashCode()
,并实现Comparable
接口。这将使您的类在进行任何类型的排序或散列时完全“兼容”,包括使用Collections.sort(
)、任何Map
类或任何Set< /代码> 类。如果该类有很小的机会被放入某种集合中,那么它肯定应该实现所有这三个方法。
请记住,如果两个对象相等,则:
compareTo()
必须返回 0。You must override
Object.equals()
andObject.hashCode()
, and also implement theComparable
interface. This will make your class fully "compliant" when doing any kind of sorting or hashing including usingCollections.sort(
), anyMap
class, or anySet
class. If there's even a tiny chance that the class will be put in some sort of collection, then it should definitely implement all three of these methods.Keep in mind that if two objects are equal, then:
compareTo()
must return 0.您必须实现 等于,hashCode ,并且(在实现Comparable 接口) compareTo。
在每种情况下,由于您有一个作为主键的字符串,因此您可以考虑简单地将这些调用分派到您的字符串。例如:
You must implement equals, hashCode, and (after implementing the Comparable interface) compareTo.
In each case, since you have a string which is a primary key, you may consider simply dispatching these calls to your string. For example:
字符串已经非常适合散列和比较,因此如果您的对象确实可以通过字符串唯一标识,那么您就处于良好状态。只需确保实现用于排序的 Comparable 接口并覆盖用于散列的 equals 和 hashCode(委托给主键字符串)即可很好,可以走了。
Strings are already very well suited for hashing and comparison, so if your objects can truly be uniquely identified by strings then you are in good shape. Just make sure to implement the
Comparable
interface for sorting and overrideequals
andhashCode
(delegating to the primary key string) for hashing and you're good to go.如果主键是
对象
,您需要决定排序顺序是基于对象
还是基于对象
的主键对象
。无论哪种情况,要排序的项目都应该实现 Comparable 接口,并使用适当的compareTo() 方法。可能性很大,这意味着您也必须重写 equals() 和 hashCode() ,因为只有某些主键对象可能具有正确的默认实现。
如果您想根据某些非自然排序顺序进行排序,那么还需要实现一些“额外”的
比较器
。有序集合
支持替代比较器
。If the primary key is an
Object
you need to decide if the sort order is based on theObject
or theObject
's Primary KeyObject
.In either case, the item to be sorted should implement the
Comparable
interface, with a propercompareTo()
method. Odds are excellent that means you'll have to overrideequals()
andhashCode()
too, as only some of the primary key Objects are likely to have proper default implementations.If you want to sort based on some non-natural sort order, then also implement a few "extra"
Comparators
. OrderedCollections
support alternativeComparators
.