0

Let's say I have a string array. In Arrays, we cannot add or remove an element without first changing the size of the array itself. We can update the element of the array but Strings are immutable. So we actually will be having a new Object.

Now in the case of Immutable Lists, the same goes, one cannot modify the list itself. We can however modify the objects of the list.

How are these two different then. When should we prefer an immutable list with Strings.

Sonali Gupta
  • 494
  • 1
  • 5
  • 20
  • 2
    You can replace an immutable object with another in an array, but you can't do that with immutable lists. – ernest_k Aug 19 '21 at 05:44
  • https://stackoverflow.com/questions/25922996/immutablelist-but-still-able-to-modify-elements-in-the-list -->. does it mean if it were a string, i will not be able to update, just because its an object I can? – Sonali Gupta Aug 19 '21 at 05:50
  • 1
    String is just a type that happens to be immutable, so yes, if your list contains strings, you would not be able to modify the list or its elements. If your immutable list contains objects of a mutable type, then you'd be able to modify elements, although you still wouldn't manage to modify the list. – ernest_k Aug 19 '21 at 05:53
  • in Layman terms, maybe in array we can have a new object replace an old object, but not in immutable lists? – Sonali Gupta Aug 19 '21 at 05:54
  • 3
    Right. That's what I meant with my first comment. – ernest_k Aug 19 '21 at 05:55
  • 1
    by the way List.of and List.copyOf() give imutable list https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html if that cover your needs –  Aug 19 '21 at 06:05

2 Answers2

3

There're two aspects here: 1) immutability in general and 2) using array vs List in Java.

Ad. 1. In addition to what @Alex mentioned, please read "Unmodifiable Lists " paragraph in the JDK documentation (starting from JDK9 you can use immutable lists out of the box if you want) and ImmutableCollectionsExplained on Guava wiki to better understand how immutability works for collections in Java.

Ad. 2. To use arrays nowadays you have to have specific reasons, so please read this answer from 2011 (still valid) by Kevin Bourrillion, Guava lead developer.

TL;DR: Use immutable lists.

Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112
1

You should prefer an immutable list with strings when you require the values to not change. Strings are immutable objects like you said so you can't change the string values in an immutable list. If the immutable list contained mutable objects then the values in the mutable objects could be changed regardless if you use immutable list or an array.

Alex
  • 710
  • 6
  • 8