java 将Arraylist对象添加到java中的哈希表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1753806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:49:57  来源:igfitidea点击:

Adding Arraylist object to hash table in java

java

提问by venkat

how to store multiple arraylist objects in hashtable in java & how do i get it back.

如何在java中的哈希表中存储多个arraylist对象以及如何取回它。

回答by ChssPly76

Don't. Use HashMapinstead of Hashtable - it's not synchronized.

别。使用HashMap而不是 Hashtable - 它不是同步的。

Map<String, ArrayList<SomeObject>> myMap = new HashMap<String, ArrayList<SomeObject>>();
ArrayList<SomeObject> list = new ArrayList<SomeObject>();
list.add(someObjectInstance1);
list.add(someObjectInstance2);
myMap.put("key1", list); // stores list containing instances #1 and #2 under key "key1"
ArrayList<SomeObject> list2 = new ArrayList<SomeObject>();
list2.add(someObjectInstance3);
myMap.put("key2", list2); // stores list2 containing instance #3 under key "key2"

SomeObject obj1 = myMap.get("key1").get(0); // returns instance #1
SomeObject obj2 = myMap.get("key1").get(1); // returns instance #2
SomeObject obj3 = myMap.get("key2").get(0); // returns instance #3

All that said, you may want to consider using Multimapfrom Google Collectionsinstead:

说了这么多,你可能要考虑使用Multimap之谷歌集合,而不是:

Multimap<String, ArrayList<SomeObject>> myMap = ArrayListMultimaps.create();
myMap.put("key1", someObjectInstance1);
myMap.put("key1", someObjectInstance2);
myMap.put("key2", someObjectInstance3);

SomeObject obj1 = myMap.get("key1").get(0); // returns instance #1
SomeObject obj2 = myMap.get("key1").get(1); // returns instance #2
SomeObject obj3 = myMap.get("key2").get(0); // returns instance #2

You can see how much more straightforward this approach is.

您可以看到这种方法更加直接。

回答by Geek

Use the Hashcode of each Linklist as the Key. Using a FOR Value mentioned in one of the posts as the Keys is probably not a good idea. What if you have to add a new List somewhere else ? You will have to traverse the entire map to find the next greatest key.

使用每个 Linklist 的 Hashcode 作为 Key。使用其中一篇文章中提到的 FOR 值作为键可能不是一个好主意。如果您必须在其他地方添加新列表怎么办?您必须遍历整个地图才能找到下一个最大的键。