سؤال

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