Hash Map with LinkedList in java

旧巷老猫 提交于 2019-12-12 17:41:49

问题


Is there a built in implementation in java for hash map whose values are linked lists?

like, if I put:

 map.put(1, "A");
 map.put(1, "B");

then it automatically add A and B to the linked list. When I retrieve from the map, as:

  map.get(1)

I get back a list containing both of them?


回答1:


Java does not have it but you can use MultiMap from Google Guava.

A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.

The methods get(K), keySet(), keys(), values(), entries(), and asMap() return collections that are views of the multimap

This article Multimaps - Google Guava gives you complete idea about how to use it and also how to do it with HashMap using List as value.




回答2:


Second put will overwrite first put. You will get B as response.

As per javadoc

If the map previously contained a mapping for the key, the old value is replaced

If you want to keep both entries, you need to use thrid party library google guava MultiMap




回答3:


Nope, just build your own.

First you take a HashMap, if the key does not exist you put the linkedList in...

Simple...



来源:https://stackoverflow.com/questions/13201898/hash-map-with-linkedlist-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!