我使用 TreeMap 类来存储消息信息及其在应用程序中的优先级。
我使用了 treeMap 类来执行此操作,因为此类会根据键值自动对元素进行排序,例如我有这种情况:
enum Priority { HIGH, MEDIUM, LOW }
TreeMap<Priority,String> tMap = new TreeMap<Priority,String>();
我使用键(消息的优先级)根据优先级严重性自动对消息进行排序,但问题是,在 TreeMap 中,键是唯一的,那么如果我尝试插入具有相同优先级的两条消息,第一个消息将被覆盖......
我如何更改此行为并禁用 TreeMap 上的唯一约束?
是否有像 TreeMap 这样的类允许为多个元素放置相同的 Key?
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 TreeMap<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 ?
发布评论
评论(4)
你不能。键的唯一性是 Map 接口的基本不变性。
您可以将其实现为
Map>
并自行管理列表。如果(例如)您想要按先进先出顺序处理给定优先级的消息,这是一个不错的选择。或者,您可以使用 MultiMap 类;例如来自 Apache 公共集合 或 < a href="http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html" rel="noreferrer">番石榴。
You can't. The uniqueness of keys is a fundamental invariant of the
Map
interface.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.查看 Google Guava 库中的 TreeMultimap 类。
Check out the TreeMultimap class in the Google Guava library.
您可能完全需要另一种集合类型。但如果您打算使用 TreeMap,那么:
1) 考虑使用更复杂的 Priority 类。也许创建一种优先级类型,它既具有基本优先级 (HIGH),又具有唯一编号,每次获得新优先级时该编号都会递增。然后使用该额外值实现 equals、hash、Comparable 等。
2) 对于每个优先级,该值可以是一个Collection。检索给定优先级的值,并将新值附加到检索到的集合的末尾。但在这一点上,使用 TreeMap 就有点大材小用了。
另外,请查看 Apache Commons Collections。
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.