开发者

TreeMap with no unique key

开发者 https://www.devze.com 2023-03-10 14:23 出处:网络
I use a TreeMap class for store messages information with their priority in my application. I\'ve used a treeMap class for do it because this class order automatically the element based on the key val

I use a TreeMap class for store messages information with their priority in my application. I've used a treeMap class for do it because this class order automatically the element based on the key value, for example i have this situation :

enum Priority { HIGH, MEDIUM, LOW }
TreeMap<Priority,String> tMap = new Tree开发者_Go百科Map<Priority,String>();

I use the key (priority of the message) for automatically order messages based on the priority severity, but the problem is that in TreeMap the key is unique then if i try to insert two messages with the same priority the first is overwritten ....

How can i change this behaviour and disable unique constraint on TreeMap?

Is there a class like TreeMap that allow to put the same Key for multiple element ?


How can i change this behaviour and disable unique constraint on TreeMap?

You can't. The uniqueness of keys is a fundamental invariant of the Map interface.

Is there a class like TreeMap that allow to put the same Key for multiple element ?

You can implement this as a Map<Priority,List<String>> and manage the lists yourself. This is a good option if (for example) you want to process the messages for a given priority in fifo order.

Alternatively, you can use a MultiMap class; e.g. from Apache commons collections or Guava.


Check out the TreeMultimap class in the Google Guava library.


You might want another collection type altogether. But if you're intent on using TreeMap, then:

1) Consider using a more complex Priority class. Perhaps create a priority type that has both the base priority (HIGH) and a unique number that's incremented every time you get a new one. Then implement equals, hash, Comparable, etc. using that extra value.

2) For each priority, the value can be a Collection. Retrieve the value for the given priority, and append the new value on the end of the retrieved collection. At that point, though, using a TreeMap is a bit of overkill.

Also, have a look at Apache Commons Collections.


You may want to use another structure rather than a treemap.

A map is a map and the behavior is what it is, so in a map you cannot have the same key twice by definition.

0

精彩评论

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

关注公众号