繁体   English   中英

番石榴Multimap。把价值放在最后和开始

[英]Guava Multimap. Put value both to the end and beginning

我使用Guava Multimap:

Multimap<Integer, String> commandMap = LinkedHashMultimap.create();
...
actionMap.put(index, "string"); // Put value at the end of list.

此命令将值放在列表的末尾。 但我需要能够在结束和开始时添加两者。 有办法解决这个问题吗?

链接的散列映射不能作为列表工作,因为它只是一个常规映射,其中保留了添加节点的顺序,供您稍后使用(例如,使用迭代器)。 这就是为什么你没有任何函数来添加带索引的元素。

如果要在LinkedHashMultimap的初始化中添加元素,则需要创建一个新元素并将旧LinkedHashMultimap所有元素添加到新的:

Multimap<Integer, String> newMap = LinkedHashMultimap.create();
newMap.put(key,valueForTheFirstIndex); // first (and only) object of new map
newMap.putAll(commandMap); // adds with the order of commandMap 
commandMap = newMap;

add all将所有其他元素添加到newMap,使valueForTheFirstIndex实际上保留在第一个索引中。 请注意,如果执行此操作,您将失去使用映射的优势,因为如果始终添加到数组的开头,则复杂性将为O(n ^ 2)。 如果要添加索引,则应在添加内容时使用列表,然后转换为linkedhashmap以便快速访问。


(无疑范围)

你在那里命名为index值不是索引,但实际上是一个键。 您没有地图中的索引。

actionMap.put(index, "string"); 

正如您可以在文档中看到的那样: http//docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/LinkedHashMultimap.html

put(K key, V value) // you don't see any reference to index there

这不是ListMultimap ,而是SetMultimap 如果需要ListMultimap ,请使用ArrayListMultimapLinkedListMultimap

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM