Sun 1 Jun 2008
A final static field references an array and can be accessed by malicious code or by accident from another package. This code can freely modify the contents of the array.
So if you declare a field like:
public static final String[] CHECKIN_CHECKOUT_DATE_PATTERN = new String[] { "MM-dd-yyyy", "MM/dd/yyyy", "MM.dd.yyyy" };
You intended the array to be final however array elements are modifiable! Oops…
The final keyword was included in the Java language to assist developers in creating immutable classes, and enable compilers and runtime environments to optimize on the basis of declared immutability. However, while fields can be final, array elements cannot.
3 Responses to “Field is a mutable array…”
Leave a Reply
You must be logged in to post a comment.
June 5th, 2008 at 2:18 pm
In this case however, aren’t String immutable always?
June 5th, 2008 at 9:36 pm
Yes, Strings are immutable, period. However this post draws attention to the fact that declaring final does not really protect the contents of array.
If a final variable holds a reference to an array, then the components of the array may be changed by operations on the array, although the variable will always refer to the same array. The same applies to collections as well. A list may be declared final and thus always exist; its content is undetermined and can be changed as needed.
June 6th, 2008 at 3:28 pm
True. The scope of the “final” applies only to the reference of the declared variable. However it contents can be manipulated/changed. If any reference under the scope of such final variable were to be made final then no modification can take place (pretty much).