我可以使用什么数据结构按多个条件对对象进行排序/比较?
我们有一个对象集合,每个对象都有一个整数 ID 和一个时间戳。我们希望能够搜索重复项并根据 ID 更新集合。
但我们还希望能够获取集合的“切片”,例如在给定时间之后查找带有时间戳的每个对象。所以我们还想根据时间戳进行排序。
我们使用的是 TreeMap,乍一看它似乎给了我们我们想要的东西。但由于 TreeMap(以及从 SortedSet 派生的所有内容)仅使用 CompareTo() 并忽略 equals() 方法,因此我们发现基于 ID 搜索重复项不起作用。我们的compareTo()方法试图同时考虑这两种情况(搜索ID或时间戳),但最终又大又难看,而且实际上不起作用。 :)
这个集合可能会变得非常大,所以我们当然希望尽可能快地搜索/排序/插入。
We have a collection of objects, each object has an integer ID and a timestamp. We want to be able to search for duplicates and update the collection based on the ID.
But we also want to be able to take a "slice" of the collection, for instance finding every object with a timestamp after a given time. So we also want to sort on the timestamp.
We're using a TreeMap, which at first seemed to give us what we wanted. But because the TreeMap (and everything deriving from SortedSet) only uses compareTo() and ignores the equals() method, we find that searching for duplicates based on ID doesn't work. Our compareTo() method tries to allow for both conditions (searching on ID OR timestamp) but ultimately is large and ugly and doesn't actually work. :)
This collection could grow very large, so of course we want as fast as possible searching / sorting / inserting.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用两个 TreeMap,一个将 ID 映射到对象,另一个将时间戳映射到对象。
然后,您可以根据对象的 id 或时间戳轻松找到对象。您还可以获得一组具有特定范围内的时间戳的对象(正如您所知)。
缺点显然是您必须从两个集合中删除对象。然而,这不应该那么糟糕,因为每个对象都知道它的 id 和时间戳,所以如果你想按时间戳删除,你可以免费获得 id,并且你只需要再做一次日志操作。
如果您愿意,可以将它们打包成您自己的收藏。
You could use two TreeMaps, one that maps ID to objects, and one that maps timestamps to objects.
Then you can easily find an object based on it's id, or on it's timestamp. You can also get a set of objects with have a timestamp in a specific range (as you already know).
The drawback is obviously that you have to remove objects from both collections. This however shouldn't be that bad, since each object knows both it's id and its timestamp, so if you want to remove by timestamp, you get the id for free, and you're just forced to do one more log-operation.
Wrap them up in a collection of your own if you like.