Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating HashTable with ArrayList as a value

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;
     }
like image 549
Shepard Avatar asked Jul 18 '26 17:07

Shepard


2 Answers

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

  }
like image 153
Amit Deshpande Avatar answered Jul 20 '26 06:07

Amit Deshpande


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();
like image 36
Yogendra Singh Avatar answered Jul 20 '26 06:07

Yogendra Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!