Why won't declaring an array final make it immutable in Java?

流过昼夜 提交于 2019-12-03 06:09:26

final is only about the reference that is marked by it; there is no such thing as an immutable array in Java. When you say

private final int[] xs = new int[20];

you won't be allowed to say

xs = new int[10];

later on. That's all what final is about. More generally, ensuring that an object is immutable is often hard work and full of a range of subtleties. The language itself doesn't give much to this end out of the box.

final means you can't change the reference - ie you can't assign another array to that field.

"Immutable" means you can't change the contents of the array - final has no effect on that.

As your code shows, you can assign a value to one of the elements of the array, which doesn't change the reference to the array

Here you are making a object reference final, not a primitive. (Arrays are special Java objects, too.) Making a reference final means that you cannot make it refer something else once it is initialized. But of course you can change the state of an object referred by a final variable.

declaring an array

In Java, we declare variables, and create objects (such as arrays). These actions are independent; we can declare a variable without creating an object, and create an object without declaring a variable.

Immutability is a property of an object, while final is a property of a variable. An object may be referred to by several variables. Which variable should govern immutability of the array object?

int[] a = {1,2,3};
final int[] b = a;
a[0] = 10; // should this be legal?

If we permit this, the supposedly immutable value of b[0] has been changed. But how can the compiler prevent this? By making it impossible to assign a non-final to a final reference? How would I initialize the array, then? I couldn't do so in a loop ...

And: What does it even mean for an array to be immutable? For instance, should the following compile?

final int[][] a = {{1,2}, {3,4}};
a[1][1] = 5;

C++ solves this by permitting const to be specified (or omitted) for each level of indirection. In Java, final can be specified (or omitted) once per variable. Yes, final is a simpler const, much like Java is a simpler C++. Let's keep it simple, shall we?

It means that a new instance of the object would not be allowed.

Farhan Syed

Like everyone commented, declaring it final will not let you assign another array to your variable. Read more here

The array itself will retain it's properties same as before.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!