I've got an ArrayList<String> and want to add to a string already in it, but not replace it. Is this possible without myArrayList.set(index, myArrayList.get(index) + "myString");? From my understanding, myArrayList.get(index) += "myString"; does not work because it is read-only.
4 Answers
The statement myArrayList.get(index) += "myString"; does not work because you are never storing it back in arraylist. Due to immutability of strings, your new string is created but it is not referred. Hence you don't find it reflected in arraylist element.
Personally, I would have chosen the first way.
Comments
Maybe you can use StringBuilder instead of String
For example,
ArrayList<StringBuilder> list = new ArrayList<StringBuilder>();
int index = 0;
list.add(new StringBuilder(""));
System.out.println(list.get(index));
list.get(index).append("once");
System.out.println(list.get(index));
list.get(index).append("-twice");
System.out.println(list.get(index));