有没有办法将元数据添加到 Java 集合中?

发布于 2024-08-24 07:31:15 字数 131 浏览 3 评论 0原文

假设我有一个对象集合,可以根据对象的不同字段使用多个不同的比较器对它们进行排序。 如果稍后能够在代码中知道使用哪个比较器对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

带上头具痛哭 2024-08-31 07:31:15

不适用于 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.

你在我安 2024-08-31 07:31:15

不,没有任何实现可以做到这一点。您需要自己跟踪它。您可以对 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.

星星的轨迹 2024-08-31 07:31:15

确定:

为您的装饰 Collection 定义方法

public List<Comparator<Foo>> getComparators() { ... }

,并

public int whichComparator() { ... }

返回 List 中当前正在使用的 Comparator。如果您要修改在对象的生命周期中可能使用哪些比较器,您可以使用 Map 和一些合理的键(例如,枚举 - 甚至可能是实现比较器的枚举)使其变得更漂亮,但是我认为以上已经是一个足够好的开始了。

sure:

define methods for your decorated Collection<Foo>

public List<Comparator<Foo>> getComparators() { ... }

and

public int whichComparator() { ... }

that returns which Comparator is currently in use from the List. You could make it fancier with a Map 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文