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.

有帮助吗?

解决方案

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.

其他提示

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));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top