final array in Java

final array in Java

final in Java affects the variable, it has nothing to do with the object you are assigning to it.

final String[] myArray = { hi, there };
myArray = anotherArray; // Error, you cant do that. myArray is final
myArray[0] = over;  // perfectly fine, final has nothing to do with it

Edit to add from comments: Note that I said object you are assigning to it. In Java an array is an object. This same thing applies to any other object:

final List<String> myList = new ArrayList<String>():
myList = anotherList; // error, you cant do that
myList.add(Hi there!); // perfectly fine. 

You are misinterpreting the final implementation. final applies to the array object reference, which means once it is initiated, the reference can never change but the array its self can be populated. Its not violating the rules you have specified only one rule about the reference change which is working accordingly. If you want the values should also never change you should go for Immutable lists i.e

List<String> items = Collections.unmodifiableList(Arrays.asList(I, can, never, change));

final array in Java

You can only make it so the array reference cant be changed. If you want the elements to be unable to be changed, you need to use an unmodifiable collection of some kind.

Leave a Reply

Your email address will not be published.