简体   繁体   English

不变的字符串和最终关键字

[英]Immutable strings and final keyword

I typically place global compile-time variables (like constants that i use such as avogadro's number or whatever) into public static final variables. 我通常将全局编译时变量(例如我使用的常数,例如avogadro的数字或其他)放入公共静态最终变量中。 However, i hadn't ever considered if this actually does anything for Strings. 但是,我从未考虑过这是否真的对Strings有作用。 Is there any point in making a String final since it's already immutable? 因为String已经是不可变的,所以使String final有什么意义吗?

It's a theoretical more than a practical question. 这不仅仅是理论问题,而是实际问题。

final is different from immutable. final不同于不变。 final means the handler (variable) cannot point to another object. final意味着处理程序(变量)不能指向另一个对象。 Immutable means the object can't change its internal state. 不可变意味着对象无法更改其内部状态。

  • static final Foo foo = new Foo(1) means you can't later have foo = new Foo(2) static final Foo foo = new Foo(1)意味着您以后不能再拥有foo = new Foo(2)
  • if Foo is immutable, it means that once you create it, you can't change its fields. 如果Foo是不可变的,则意味着一旦创建Foo ,就无法更改其字段。 Eg you can't have Foo foo = new Foo(1); foo.setValue(3); 例如,您不能拥有Foo foo = new Foo(1); foo.setValue(3); Foo foo = new Foo(1); foo.setValue(3);

You're getting the reference to the string and the actual string confused. 您正在获得对该字符串的引用,而实际的字符串却被混淆了。 Immutable describes the actual string object and means you can't change the value of that object. 不可变描述了实际的字符串对象,这意味着您无法更改该对象的值。 Final refers to the reference to a string object and means that you can't change what string that reference is pointing to. Final引用了对字符串对象的引用,这意味着您无法更改引用所指向的字符串。 Consider the following code: public static String str = "happy"; 考虑以下代码:public static String str =“ happy”; ... str = "sad"; ... str =“悲伤”;

This code creates two string objects, one that contains the value "happy" and one that contains the value "sad". 此代码创建两个字符串对象,一个包含值“ happy”,一个包含值“ sad”。 Neither of these objects (because Strings are immutable) can be changed. 这些对象(因为字符串是不可变的)均不能更改。 str is a reference and can be made to point to either of these objects; str是一个引用,可以指向这些对象中的任何一个; however, were we to change the first line of code to: public static final String str = "happy"; 但是,我们是否将代码的第一行更改为:public static final String str =“ happy”; str = "sad" would no longer be legal. str =“ sad”将不再合法。 Because we have changed str to be a final variable, it cannot be made to point to different objects. 由于我们已将str更改为最终变量,因此无法使其指向不同的对象。

final only applies to the reference. final仅适用于参考。 If you declare an Object final it doesn't mean that the object can't be changed, it disallows the reference to the object to be changed. 如果声明一个Object final,则并不意味着不能更改该对象,而是不允许引用要更改的对象。 It's not the same thing as immutable. 这与不变是不同的。

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

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