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?
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.
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.
You can easily edit the information in the static String[]. Then you can manipulate a specific entry as you please.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With