Modifying a public static destination array

When developing a small API, I was going to write a static value that refers to an array of String: public static final String[] KEYS={"a","b","c"} I found that this is indicated as a "security hole" in the article 14 "Effective Java" by Joshua Bloch, where he offers an alternative by declaring an array of te 'private' and providing a public receiver that returns an unmodifiable list:

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

I just can’t understand why this is necessary, the array in the original expression is declared final, even if its publication and its elements are immutable, how can this be changed from the outside of the code?

+5
source share
4 answers

An array is not immutable.

You can still write:

 KEYS[0] = "d"; 

without any problems. final means you cannot write:

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

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

+8
source

final funds

You cannot change the basket. However, you can change the fruits inside.

A recycle bin is your instance of an array. Fruits are your keys inside.

In the first case, from another place in the code, I can do

 ClassName.KEYS[2] ="MyOwnValue"; 

But you cannot change when it is an unmodifiable list.

Take a snapshot to read: Why is the class variable of the final instance in Java?

+4
source

While the reference to the array is immutable (you cannot replace it with a reference to another array), and the strings themselves are also immutable, but you can still write

 KEYS[0] = "new Key"; 
0
source

A composite object (array, Set , List , etc.), which is final , does not mean that its composite objects will not be changed - you can still modify composite objects. final for a composite object simply means that its reference cannot be changed.

In your case, the KEYS value cannot be changed, but KEYS[0] , etc. can change.

0
source

Source: https://habr.com/ru/post/1239411/


All Articles