If you are trying to create an array whose cells (or subarrays) cannot be changed, you are out of luck. The cells of a Java array are always mutable.
If you need immutability at that level, your best option is to create an immutable
wrapper class for the array:
For a 1-D array, I'd recommend Collections.unmodifiableList
, or Guava immutable collections. (The distinction between immutable and unmodifiable could be significant.)
For an array with higher dimensions, you may need to build a custom class to represent the data structure with the desired characteristics. There are existing implementations out there, but they may not have the right model for your use-case. (Search for "java immutable matrix" and so on.)
If you are happy with the data structure as is (and its mutability characteristics), and you are trying to address the compilation error in the example, read on.
The problem with your current attempt is actually nothing to do with the way that primitives or arrays work. The problem is simply that you are trying to assign to a final
after it has been initialized. You can't do that Java.
There are two solutions in this particular case:
If the initialization (e.g. the arrays' sizes) does not depend on anything that main
is supplying, simply move the array initialization into the classes static initialization; e.g. as proposed by Juvanias.
If the initialization depends on stuff in main
, then you will need to make the array variables into final
instance variables, and do the initialization in a constructor.