【问题标题】:Adding items to a Hashtable LinkedList将项目添加到 Hashtable LinkedList
【发布时间】:2012-12-08 04:23:21
【问题描述】:
我有一个哈希表map,每个元素中都有LinkedLists(按照here 的解释实现单独的链接)。我该如何为表中的每个 LinkedList 元素添加新节点?
我正在绞尽脑汁,我不认为
map.get(index).add(new Object);
会起作用,仅仅是因为 Hashtable 的 get() 方法获取键的值,而不是相反...
【问题讨论】:
标签:
java
linked-list
hashtable
【解决方案1】:
map.get(index).add(new Object);
只要index 是键而不是计数器,并且您的链表是针对该键存储的,那么该语句就可以正常工作。
Map 将数据存储在 (Key, Value) 对中,而数组存储在可通过计数器访问的连续位置。
【解决方案2】:
假设
Map<KeyClass,List<Item>> map = new HashMap<KeyClass,List<Item>>();
试试
KeyClass key = ...;
List<Item> list = map.get(key);
if (list == null)
{
list = new LinkedList<Item>();
map.put(key,list);
}
list.add(...whatever...);