I am trying to understand what happens if I reassign a value to array element which is final, this is the code :
public class XYZ {
private static final
Arrays
are mutable Objects unless created with a size of 0.Therefore,you can change the contents of an array.final
only allows you to prevent the reference from being changed to another array Object.
final String[] ABC ={"Hello"};
ABC[0]="Hi" //legal as the ABC variable still points to the same array in the heap
ABC = new String[]{"King","Queen","Prince"}; // illegal,as it would refer to another heap Object
I suggest you use Collections.unmodifiableList(list)
to create a immutable List.See the javadoc here (unmodifibale list).
You can do the following
String[] ABC = {"Hello"};
List listUnModifiable = Collections.unmodifiableList(java.util.Arrays.asList(ABC));
At any point of time,you can get the array by calling listUnModifiable.toArray();