变量的Java final关键字 [英] Java final keyword for variables

查看:157
本文介绍了变量的Java final关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

在Java中,术语 final 是指引用,而不可变是指对象。将 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.

例如:

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 和不可变。

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

这篇关于变量的Java final关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆