7

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?

JBoy
  • 5,398
  • 13
  • 61
  • 101

4 Answers4

12

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.

Hendrik
  • 5,085
  • 24
  • 56
  • 1
    Upvoted for explaining `final`, seems like a lot of people don't understand that keyword. – Manu Dec 29 '15 at 09:10
5

final means

You can't change the Basket. Still you can change the fruits inside.

Basket is your Array instance. Fruits are your keys inside.

In first case, from somewhere else in the code, I can do

ClassName.KEYS[2] ="MyOwnValue";

But you can't modify when it is unmodifiable list.

Give a shot to read : Why final instance class variable in Java?

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

While the array reference itself is immutable (you cannot replace it with a reference to another array) and the Strings themselves are immutable too it is still possible to write

KEYS[0] = "new Key";
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34
0

A composite object ( array , Set , List etc ) being final doesn't mean that its constituent objects will not be changed - you can still change constituent objects . final for a composite object simply means that its reference can't be changed.

For your case, value of KEYS can't be changed but KEYS[0] etc can be changed.

Sabir Khan
  • 9,826
  • 7
  • 45
  • 98