开发者

Is there any use of making an array final (immutable) in Java?

开发者 https://www.devze.com 2023-03-16 21:08 出处:网络
Is there any reason why one would declare a array开发者_高级运维 final? say something like this

Is there any reason why one would declare a array开发者_高级运维 final? say something like this

final int[] array={1,2,33,21,11};


There may be several. At least, it ensures that

  • later code cannot point the variable 'array' to another array
  • the variable 'array' can be seen by anonymous inner classes (e.g. listeners).

Importantly, it does not ensure that the contents of 'array' are immutable.


It provides an invariant that the assignment of 'array' can't be changed. (When looking at code I can assume 'array' won't get reassigned). However nothing stops an element from being changed. Ex. array[2] can be changed from 33 to 25.


You can't. You can only declare the array reference final, which has nothing to do with making the array immutable. Arrays are never immutable in Java.


The reasons are the same as with any other mutable type: the reference stays the same throughout the lifecycle of the declaring object, so you can distribute it freely for example. final is always about the reference being fixed and not the contents, which might change.

With arrays, you even get a guarantee that the array size isn't going to change, although how useful that guarantee is depends on the specific use case.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号