【发布时间】:2013-08-18 17:44:34
【问题描述】:
Hashtable<Integer,String> ht = new Hashtable<Integer,String>();
ht.put(1,"student1");
ht.put(1,"student2");
如何遍历“单个键”的所有值?
key:1
values: student1, student2
【问题讨论】:
标签: java loops hashtable key-value
Hashtable<Integer,String> ht = new Hashtable<Integer,String>();
ht.put(1,"student1");
ht.put(1,"student2");
如何遍历“单个键”的所有值?
key:1
values: student1, student2
【问题讨论】:
标签: java loops hashtable key-value
你需要使用:
Hashtable<Integer, List<String>> ht = new Hashtable<Integer, List<String>>();
并在关联的List 中为特定键添加新的字符串值。
话虽如此,您应该使用HashMap 而不是Hashtable。后者是遗留类,它早已被前者取代。
Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
然后在插入新条目之前,使用Map#containsKey() 方法检查键是否已经存在。如果键已经存在,则获取相应的列表,然后为其添加新值。否则,放置一个新的键值对。
if (map.containsKey(2)) {
map.get(2).add("newValue");
} else {
map.put(2, new ArrayList<String>(Arrays.asList("newValue"));
}
如果可以使用 3rd 方库,另一种选择是使用 Guava's Multimap。
Multimap<Integer, String> myMultimap = ArrayListMultimap.create();
myMultimap.put(1,"student1");
myMultimap.put(1,"student2");
Collection<String> values = myMultimap.get(1);
【讨论】:
Arrays 类中查看该方法的文档。
Hashtable 不会为单个键存储多个值。
当你写 ht.put(1, "student2") 时,它会覆盖 "1" 的值,并且不再可用。
【讨论】:
哈希表不允许一个键有多个值。当您向键添加第二个值时,您将替换原始值。
【讨论】:
如果您希望单个键有多个值,请考虑使用 ArrayLists 的 HashTable。
【讨论】: