Java中的最终变量操作 [英] Final variable manipulation in Java
问题描述
有人可以告诉我在Java的上下文中以下行的含义是什么:
Could anyone please tell me what is the meaning of the following line in context of Java:
最终变量仍然可以是
操纵,除非它是不可变的
final variable can still be manipulated unless it's immutable
据我所知,通过将任何变量声明为final,你不能再改变它,然后他们在上面的行中用不可变这个词是什么意思?
As far as I know, by declaring any variable as final, you can't change it again, then what they mean with the word immutable in above line?
推荐答案
这意味着如果你的最终变量是一个引用类型(即不是像int这样的原语),那么它只是无法更改的引用。它不能被引用到不同的对象,但是如果类允许的话,它所引用的对象的字段仍然可以被改变。例如:
It means that if your final variable is a reference type (i.e. not a primitive like int), then it's only the reference that cannot be changed. It cannot be made to refer to a different object, but the fields of the object it refers to can still be changed, if the class allows it. For example:
final StringBuffer s = new StringBuffer();
StringBuffer的内容仍然可以随意更改:
The content of the StringBuffer can still be changed arbitrarily:
s.append("something");
但你不能说:
s = null;
或
s = anotherBuffer;
另一方面:
final String s = "";
字符串是不可变的 - 根本没有任何方法可以让你更改字符串(除非你使用反射 - 然后去地狱)。
Strings are immutable - there simply isn't any method that would enable you to change a String (unless you use Reflection - and go to hell).
这篇关于Java中的最终变量操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!