StrugglingCSmajor
StrugglingCSmajor

Reputation: 5

Cannot figure out why ArrayList.add() isn't working for me

public void findWord(String word) {
  wordsOnBoard = new ArrayList<String>();
  if (dictionary.contains(word)) {
    System.out.println(word);
    wordsOnBoard.add(word); 
  } else {
    System.out.println("None found");
  }
  System.out.println(wordsOnBoard);
}

wordsOnBoard is a global ArrayList

When the dictionary.contains(word) it prints out the word and then adds it to wordsOnBoard but then when it leave the if loop the word is no longer in the ArrayList wordsOnBoard. How would I fix this?

Upvotes: 0

Views: 121

Answers (3)

Qaiser Habib
Qaiser Habib

Reputation: 61

Remove this line: wordsOnBoard = new ArrayList();

from the function and put it where the global variable is actually defined.

When your function comes into scope, this wordsOnBoard will get a local ArrayList with a lifecycle limited to the lifecycle of the function itself. Once the function exits, Garbage Collection will destroy that object.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201429

You're not returning your List, I suggest you try

// pass in your List reference, and then it won't go out of scope.
public void findWord(List<String> wordsOnBoard, String word) {
  if (dictionary.contains(word)) {
    System.out.println(word);
    wordsOnBoard.add(word); 
  } else {
    System.out.println("None found");
  }
  System.out.println(wordsOnBoard);
}

Or, you could make wordsOnBoard a field in your class.

Upvotes: 0

Joachim Sauer
Joachim Sauer

Reputation: 308001

You're creating a new ArrayList each time you enter the method.

Then you add something to it (sometimes) and as soon as you leave the method, the object will be eligible for GC.

If you want to keep it around, you should probably put the ArrayList into a field of the class.

Upvotes: 2

Related Questions