문제

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