简体   繁体   English

在 Java 中使数组最终(不可变)有什么用?

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

Is there any reason why one would declare a array final?有什么理由可以声明一个数组 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 (eg listeners).匿名内部类(例如侦听器)可以看到变量“数组”。

Importantly, it does not ensure that the contents of 'array' are immutable.重要的是,它不能确保 'array' 的内容是不可变的。

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. array[2] 可以从 33 更改为 25。

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.原因与任何其他可变类型相同:引用在声明 object 的整个生命周期中保持不变,因此您可以自由分发它。 final is always about the reference being fixed and not the contents, which might change. final总是关于固定的参考,而不是可能改变的内容。

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.使用 arrays,您甚至可以获得数组大小不会改变的保证,尽管该保证的有用程度取决于具体的用例。

You can't.你不能。 You can only declare the array reference final, which has nothing to do with making the array immutable.您只能将数组引用声明为final,这与使数组不可变无关。 Arrays are never immutable in Java. Arrays 在 Java 中永远不会不可变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM