有没有办法将元数据添加到 Java 集合中?
假设我有一个对象集合,可以根据对象的不同字段使用多个不同的比较器对它们进行排序。 如果稍后能够在代码中知道使用哪个比较器对 Collection 进行排序以及它是升序还是降序,那就太好了。有没有办法优雅地做到这一点,而不是使用一堆布尔值来跟踪事物?
Let's say I have a collection of objects which can be sorted using a number of different comparators based on the different fields of the object.
It would be nice to be able to know later on in the code which comparator was used to sort the Collection with and if it was ascending or descending. Is there anyway to do this elegantly instead of using a bunch of Booleans to keep track of things?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不适用于 Collection 接口,但如果您使用 SortedSet 有一个 comparator() 方法,您可以在其中请求其比较器。
否则,您必须对正在使用的集合类进行子类化以添加所需的访问器。
Not for the Collection interface, but if you use a SortedSet there's a comparator() method where you can ask for its comparator.
Otherwise you'll have to subclass the collection class you're using to add the accessors you need.
不,没有任何实现可以做到这一点。您需要自己跟踪它。您可以对 Collection 实现进行子类化以添加保存此信息的字段。
您还可以根据需要使用 Map 将实现映射到元数据 - 特别是您似乎希望 IdentityHashMap 执行此操作,因为您不希望比较两个不同的集合是否相等,如下所示键与 equals()。
我将存储一个布尔值(升序/降序),以及对用于排序的比较器的引用(如果这完全决定了排序)。或者,如果它是按字段排序的,则可能存储一个命名该字段的字符串。
No there's nothing with the implementations that does this. You would need to track it yourself. You could subclass a Collection implementation to add fields which hold this information.
You could also map the implementations to metadata as you like with a Map -- in particular it seems like you want IdentityHashMap to do this, since you don't want two different collections to be compared for equality as keys with equals().
I would store a boolean (ascending/descending), and a reference to the Comparator used to sort, if that's what completely determines the sort. Or if it's sorted on field, store a String naming the field perhaps.
确定:
为您的装饰
Collection
定义方法,并
返回
List
中当前正在使用的Comparator
。如果您要修改在对象的生命周期中可能使用哪些比较器,您可以使用Map
和一些合理的键(例如,枚举 - 甚至可能是实现比较器的枚举)使其变得更漂亮,但是我认为以上已经是一个足够好的开始了。sure:
define methods for your decorated
Collection<Foo>
and
that returns which
Comparator
is currently in use from theList
. You could make it fancier with aMap
and some sensible keys (say, enums - perhaps even enums which implement the comparators) if you're modifying which comparators might be used over the life of the object, but I think the above is a good enough start.