Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modifying a public static final array

Tags:

java

arrays

final

While designing a small API, i was about to write a static value that references to an array of String: public static final String[] KEYS={"a","b","c"} I have found this to be marked as a 'security hole' in Joshua Bloch's 'Effective Java' item 14, where he proposes as an alternative, declaring te array 'private' and provide a public getter that returns an unmodifiable list:

return Collections.unmodifiableList(Arrays.asList(KEYS))

I just cant see why would this be necessary, the array in the initial statement is declared final even though its public, and its elements are immutable, how could that be modified from an external piece of code?

like image 933
JBoy Avatar asked Dec 29 '15 09:12

JBoy


People also ask

Can you modify a final array in Java?

So a final array means that the array variable which is actually a reference to an object, cannot be changed to refer to anything else, but the members of the array can be modified.

Can final list be modified?

When a variable is declared with the final keyword, its value can't be modified, essentially, a constant. Immutability: In simple terms, immutability means unchanging overtime or being unable to be changed. In Java, we know that String objects are immutable means we can't change anything to the existing String objects.

Can you change values of static array in Java?

You can easily edit the information in the static String[]. Then you can manipulate a specific entry as you please.

Can we add elements in final array in Java?

In Java, Arrays are mutable data types, i.e., the size of the array is fixed, and we cannot directly add a new element in Array.


1 Answers

The array is not immutable.

You can still write:

KEYS[0] = "d";

without any issues. final just means you cannot write:

KEYS = new String[]{"d"};

I.e. you cannot assign a new value to the variable KEYS.

like image 176
Hendrik Avatar answered Oct 22 '22 04:10

Hendrik