Java string array versus Guava ImmutableList

256 Views Asked by At

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.

2

There are 2 best solutions below

0
On

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.

0
On

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.