简体   繁体   中英

modifying a public static final array

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?

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"};

Ie you cannot assign a new value to the variable KEYS .

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?

虽然数组引用本身是不可变的(你不能用对另一个数组的引用替换它)而且字符串本身也是不可变的,但它仍然可以写

KEYS[0] = "new Key";

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM