static final String[] is not final ?
Lets take final variable and try to assign new value to it. Well , we 'll have no luck here - "cannot assign a value to final variable myVar" yet at compilation stage. But having a deal with final arrays is something different. Here is an example :
class FinalArrayOutput will be "aaa". It is still not possible to do something like
{
public static final String[] array = {"a", "b","c"};
public static void main(String args[])
{
array[0] = "aaa";
System.out.println(array[0]);
}
}
String[] some_array = {"aaa", "bbb","ccc"};
array = some_array;
but possible per-element assigning new values to final array elements:
class FinalArraySo, it is final, you say ?
{
public static final String[] array = {"a", "b","c"};
public static void main(String args[])
{
String[] some_array = {"aaa", "bbb","ccc"};
for(int i=0;i<length;i++)
{
array[i] = some_array[i];
}
for(String element: array)
{
System.out.println(element);
}
}
}

7 comments:
final object does not mean immutable! final only means you cannot create a new or re-point to another instance of the object... background on pointers and memory addresses comes in handy here.
Hi Salman, thanks for comment.
Well, you are rigth. Java Language Spec is very heplful here :
http://java.sun.com/docs/
books/jls/third_edition/
html/typesValues.html#4.12.4
But in some situations static final Object[] could be security hole...
If you want the elements to be immutable, make it an immutable collection.
Hi Jim !
Yep, I see... There are a few methods with names starting with unmodifiable* at java.util.Collections. It seems to be it is the best choise to provide read-only data for user.
Is there a way to create a multidimensional array in Java as a constant? It seems that this is not possible
@Christoph
I think you should consider immutable collections.
dw
Post a Comment