Populating HashTable with ArrayList as a value
Solution 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 your neighb
e.g.
List<String> newList = new ArrayList<String>();
newList.addAll(neighb);
data.put(words.get(i), newList);
newList.clear();
Solution 2
You can not use same reference to put inside HashTable
for all keys. Each time you call clear()
it clears list that you have added which is same for all keys. 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
}
Shepard
Updated on June 04, 2022Comments
-
Shepard almost 2 years
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; }