Java 变量的final关键字

发布于 2024-10-02 23:54:24 字数 108 浏览 7 评论 0原文

final 关键字如何不使变量不可变? 维基百科说没有。

How does the final keyword not make a variable immutable? Wikipedia says it doesn't.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

寄风 2024-10-09 23:54:25

尽管不建议这样做,但 Java 允许使用反射修改最终变量。

Although it's not recommended, Java allows final variables to be modified using reflection.

无声情话 2024-10-09 23:54:25

假设您已声明 myList 是最终的。您仍然可以向 myList 添加新项目,因此它的状态不是一成不变的。由于 Final 关键字,您不能做的是更改 myList 以引用不同的列表。

Suppose you have declared that myList is final. You can still add new items to myList, so its state is NOT immutable. What you can't do, because of the final keyword, is to change myList to refer to a different list.

此刻的回忆 2024-10-09 23:54:25

阅读维基百科文章的其余部分:

为了说明最终性并不
保证不变性:假设我们
替换三个位置变量
与单个:
公开最终头寸 pos;其中 pos 是具有三个属性的对象
pos.x、pos.y 和 pos.z。然后 pos
不能分配给,但三个
属性可以,除非它们是最终的
他们自己。

Read the rest of the Wikipedia article:

To illustrate that finality doesn't
guarantee immutability: suppose we
replace the three position variables
with a single one:
public final Position pos; where pos is an object with three properties
pos.x, pos.y and pos.z. Then pos
cannot be assigned to, but the three
properties can, unless they are final
themselves.

风筝在阴天搁浅。 2024-10-09 23:54:25

因为如果引用是最终的,您仍然可以更改引用所指向的对象中的内容。您只是无法更改参考。

because if a reference is final, you can still change things in the object to which the reference points. You just cant change the reference.

如痴如狂 2024-10-09 23:54:25

对于诸如 int、double、char 等原语,它的工作原理可能更符合您的预期。

private final int status = 10;
status = 20; // WONT COMPILE because status is final

For primitives such as int, double, char etc it works more as you might expect.

private final int status = 10;
status = 20; // WONT COMPILE because status is final
仅一夜美梦 2024-10-09 23:54:24

在Java中,术语final指的是引用,而immutable指的是对象。将final修饰符分配给引用意味着它不能更改为指向另一个对象,但如果对象本身是可变的,则可以对其进行修改。

例如:

final ArrayList<String> arr = new ArrayList<String>();
arr.add("hello"); // OK, the object to which arr points is mutated
arr = null; // Not OK, the reference is final and cannot be reassigned to

正如维基百科文章提到的,如果您来自 C++,则必须将 const 的概念分解为 final 和不可变的。

In Java, the term final refers to references while immutable refers to objects. Assigning the final modifier to a reference means it cannot change to point to another object, but the object itself can be modified if it is mutable.

For example:

final ArrayList<String> arr = new ArrayList<String>();
arr.add("hello"); // OK, the object to which arr points is mutated
arr = null; // Not OK, the reference is final and cannot be reassigned to

As the Wikipedia article mentions, if you are coming from C++, you must dissociate the concept of const into final and immutable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文