I am having a little trouble understanding the concept of final in Java.
I have a class that follows:
public class MyClass
{
private int[][] myArray; // intended to be changed
private final int[][] MYARRAY_ORIGINAL; // intended to be unchangable
public MyClass(int[][] array)
{
myArray = array;
MYARRAY_ORIGINAL = array;
}
}
I was under the understanding that final would make MYARRAY_ORIGINAL read only. But I have tried editing myArray, and it edits MYARRAY_ORIGINAL as well. My question is, in this context, what exactly does final do? And for extra credit, how can I copy the array passed through the constructor into MYARRAY_ORIGINAL so that I can have 2 arrays, one to edit, and one that will remain preserved?
Your
final MYARRAY_ORIGINALis indeed read only: you can’t assign a new value to theMYARRAY_ORIGINALreference in other side than class constructor or attribute declaration:The values inside the array are not final. Those values can change anytime in the code.
If you indeed need a List of final elements, in other words, a List whose elements can’t be modified, you can use
Collections.unmodifiableList:The last piece of code was taken from here: Immutable array in Java