Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Strings in java are immutable. The involvement of an ArrayList is irrelevant to the issue. You could use an ArrayList< StringBuilder > for your use case, I guess.

myArray.get( i ).append( "foo" );

String is a immutable class ,so you can not do it , if you add an element ,you can call myArrayList.add(element) or myArrayList.add(index, element)

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));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top