Java LinkedList作为哈希表的值

Java LinkedList作为哈希表的值,java,hash,hashtable,Java,Hash,Hashtable,我创建了一个哈希表,其中一个字符串作为键,一个字符串链接列表作为值。以下是我的实现: Hashtable <String, LinkedList<String>> table = new Hashtable <String, LinkedList<String>>(); 现在我开始搞不清楚如何添加到我的LinkedList中 我是这么想的: LinkedList <String> temp = table.get(sortedWo

我创建了一个哈希表,其中一个字符串作为键,一个字符串链接列表作为值。以下是我的实现:

 Hashtable <String, LinkedList<String>> table = new Hashtable <String, LinkedList<String>>();
现在我开始搞不清楚如何添加到我的LinkedList中

我是这么想的:

 LinkedList <String> temp = table.get(sortedWord) //if null, then nothing in list
 if(temp==null) 
     table.put(sortedWord,temp.add(originalWord));

 This is not working since its not following the library functions but I'm unsure of how I would do this.
LinkedList temp=table.get(sortedWord)//若为null,则列表中无任何内容
if(temp==null)
表put(分类词、临时添加词(原始词));
这是不工作的,因为它没有遵循库函数,但我不确定我将如何做到这一点。

这是我的解决方案。解决方案是循环遍历单词,使用
Array.sort()
对字符进行排序。检查哈希表中是否填充了已排序的单词,并从中创建
LinkedList
,然后将元素添加或添加到已创建的LinkedList中。不确定为什么选择
LinkedList
作为数据结构

Hashtable <String, LinkedList<String>> table = new Hashtable <String, LinkedList<String>>();

for(String s : new String[]{"cat","dog","mouse", "cat"})
{
     char[] chars = s.toCharArray();
     Arrays.sort(chars);
     String sorted = new String(chars);

     if(table.containsKey(sorted))
     {
         LinkedList<String> list = table.get(sorted);
         list.add(s);
     }
     else
     {
         LinkedList<String> list = new LinkedList<String>();
         list.add(s);
         table.put(sorted, list);
     }
}
使用此问题对字符进行排序

你可以做:

if(!table.containsKey(sorted)) {
     table.put(new LinkedList<String>())
}
table.get(sorted).add(...)
if(!table.containsKey(已排序)){
table.put(新的LinkedList())
}
table.get(排序).add(…)

此代码的问题:

 LinkedList <String> temp = table.get(sortedWord) //if null, then nothing in list
 if(temp==null) 
     table.put(sortedWord,temp.add(originalWord));

Arrays.asList
似乎是创建只包含一个元素的列表的最简单方法。但它不会是
LinkedList
,因此您需要额外的构造函数调用来创建
LinkedList

如果您的值是单值,那么您可以直接使用Hashtable=new Hashtable();但是,如果文本文件包含多个排序时相同的单词,该怎么办?这就是为什么我想要一个LinkedList作为值fyi,我们通常使用
HashMap
而不是
Hashtable
,除非这是一个多线程程序。看。这是一个编程错误,因为“现在我只是不知道如何添加到我的LinkedList中。”我认为问题还没有那么复杂。好的,谢谢你修复它。请注意,第一个
table.put(sorted,list)
并没有完成任何任务。散列映射中的值已经是对
列表的引用,您只需将其自身替换即可。当然,第二个是必要的。我知道,但有时为了可读性增加参考会更清楚。我也做了同样的事情!非常感谢你!Def。把一切都清理干净!
if(!table.containsKey(sorted)) {
     table.put(new LinkedList<String>())
}
table.get(sorted).add(...)
 LinkedList <String> temp = table.get(sortedWord) //if null, then nothing in list
 if(temp==null) 
     table.put(sortedWord,temp.add(originalWord));
if (temp == null) {
    LinkedList<String> newList = new LinkedList<>(Arrays.asList(originalword));
    table.put(sortedWord, newList);
} else {
    // you have a LinkedList, add the word to it