我创建了一个哈希表,其中一个字符串作为键,一个字符串链接列表作为我的值。这是我的实现:
Hashtable <String, LinkedList<String>> table = new Hashtable <String, LinkedList<String>>();
我想要做的是对单词文件进行排序,并将每个排序的单词存储到哈希表(代表键)中,并将原始单词存储为我的 LinkedList 值的一部分。
例如,如果单词是
"cat"
Sorted = "act"
Store in Hashtable (key : act, value : cat);
现在我只是对如何添加到我的 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.
最佳答案
这是我的解决方案。解决方案是循环遍历单词,使用 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);
}
}
这将产生以下哈希表。
{act=[cat, cat], emosu=[mouse], dgo=[dog]}
使用此问题对字符进行排序。
关于java - LinkedList 作为 Hashtable 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33820077/