我在程序中创建HashTable时遇到问题,我正在创建WordLadder游戏。 基本上我希望我的HashTable包含唯一单词的键,值是单字母差异的单词。问题是,当我打印出来检查我要放入的内容时,它会完美地打印出我想要的内容,但是当我返回HashTable时,它会让我觉得无用。
我生成HashTable的代码如下:
public Hashtable<String, ArrayList<String>> findNeighbors(){
Hashtable<String, ArrayList<String>> data = new Hashtable<String, ArrayList<String>>();
ArrayList<String> neighb = new ArrayList<String>();
for(int i=0; i < 5; i++){
for(int j=0; j < 5; j++){
if (isNeighbor(words.get(i), words.get(j))) {
neighb.add(words.get(j));
}
}
data.put(words.get(i), neighb);
//System.out.println(words.get(i)+ " "+data.get(words.get(i))); <This Works perfectly fine
System.out.println(data.toString()); //<This returns nonsense
neighb.clear();
}
return data;
}
public boolean isNeighbor(String a, String b){
int diff = 0;
for (int i = 0; i < a.length(); i++){
if(a.charAt(i) != b.charAt(i)){
diff++;
}
}
return diff==1;
}
答案 0 :(得分:2)
您不能使用相同的引用将HashTable
放在所有键中。每次调用clear()
时,它都会清除您添加的列表,这些列表对于所有键都是相同的。 So create ArrayList for each key
for(int i=0; i < 5; i++){
ArrayList<String> neighb = new ArrayList<String>();<-- Move inside loop
for(int j=0; j < 5; j++){
if (isNeighbor(words.get(i), words.get(j))) {
neighb.add(words.get(j));
}
}
data.put(words.get(i), neighb);
//System.out.println(words.get(i)+ " "+data.get(words.get(i))); <This Works perfectly fine
System.out.println(data.toString()); //<This returns nonsense
}
答案 1 :(得分:1)
查看neighb.clear();
,您正在调用放在Hashtable中的同一个对象。您将列表放入Hashtable后立即清除列表。你想创建一个新的本地arraylist,将所有元素添加到新的arraylist add然后在Hashtable中添加新的arraylist然后清除你的neighb
例如。
List<String> newList = new ArrayList<String>();
newList.addAll(neighb);
data.put(words.get(i), newList);
newList.clear();