开发者

What data structure can I use for sorting/comparing objects by multiple criteria?

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 I开发者_如何学JAVAD.

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜