在Java中定义最终的String是否有意义? [英] Does it make sense to define a final String in Java?
问题描述
可能重复:
字符串和终结符
Possible Duplicate:
String and Final
来自 http://docs.oracle.com /javase/6/docs/api/java/lang/String.html 我可以看到:
Strings are constant; their values cannot be changed after they are created.
这是否意味着final String
在Java中实际上没有意义,因为final
属性在某种程度上是多余的?
Does this mean that a final String
does not really make sense in Java, in the sense that the final
attribute is somehow redundant?
推荐答案
String
对象是不可变的,但实际上是对可以更改的String
对象的引用.
The String
object is immutable but what it is is actually a reference to a String
object which could be changed.
例如:
String someString = "Lala";
您可以重新分配此变量保存的值(以使其引用其他字符串):
You can reassign the value held by this variable (to make it reference a different string):
someString = "asdf";
但是,与此有关:
final String someString = "Lala";
那么上述重新分配将是不可能的,并且会导致编译时错误.
Then the above reassignment would not be possible and would result in a compile-time error.
这篇关于在Java中定义最终的String是否有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!