0

I am using an ArrayList for a program, called wordList. I have a separate ArrayList for another method, called smallestWords. I do "smallestWords = arrayList" in order to have a copy of wordList that I can modify without affecting the original. However, whenever I modify smallestWords, it also modifies wordList, which is causing me issues. I'm assuming it's because setting smallestWords equal to wordList just sets it equal to that memory location, since it's an abstract data type, and gets passed by reference.

How can I make it so I get a copy of the data without being able to modify it? If you want to see the actual code for the program just ask.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Colin Null
  • 111
  • 3
  • 8

2 Answers2

2

You are not copying with smallestWords = arrayList . You are just assigning the same ArrayList to smallestWords

You should use below method to copy:

List<String> smallestWords = new ArrayList<String>(arrayList);
Salih Erikci
  • 5,076
  • 12
  • 39
  • 69
0

If you want to make a copy of an ArrayList, you can use:

ArrayList smallestWords = new ArrayList(wordList);

(insert generic type parameters as appropriate)

khelwood
  • 55,782
  • 14
  • 81
  • 108