我使用番石榴多图:
Multimap<Integer, String> commandMap = LinkedHashMultimap.create();
...
actionMap.put(index, "string"); // Put value at the end of list.
此命令将值放在列表的末尾。但我需要能够同时添加到结尾和开头。有没有办法解决这个问题?
链接的 hashmap 不能作为列表工作,因为它只是一个常规映射,其中保留了添加节点的顺序,供您以后使用(例如使用迭代器)。这就是为什么您没有任何功能来添加具有索引的元素。
如果要在 a 的开头添加一个元素,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
,请使用ArrayListMultimap
或LinkedListMultimap
。