I am having problems with creating HashTable in my program, I am creating WordLadder game.
Basically I want my HashTable to contain key which is unique word and value would be words which are one letter difference. Problem is that when I print out to check what I am putting into it, it prints perfectly what I want, however when I return HashTable it returns me nonsense.
My code for generating HashTable is following:
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;
}
Look at
neighb.clear();, You are calling on the same object you put in your Hashtable. You are clearing your list soon after putting it in the Hashtable. May you want to create a new local arraylist, add all elements to the new arraylist add then add the new arraylist in Hashtable and then clear yourneighbe.g.