Java不可变字符串混乱 [英] Java immutable strings confusion

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

问题描述

如果 String 在Java中是不可变的,那么我们怎么写成:

If Strings are immutable in Java, then how can we write as:

String s = new String();
s = s + "abc";

推荐答案

您的字符串变量不是字符串.这是对String实例的引用.

Your string variable is NOT the string. It's a REFERENCE to an instance of String.

亲自看看:

String str = "Test String";
System.out.println( System.identityHashCode(str) ); // INSTANCE ID of the string

str = str + "Another value";
System.out.println( System.identityHashCode(str) ); // Whoa, it's a different string!

str变量所指向的实例是不可变的,但是该变量可以指向您想要的String的任何实例.

The instances the str variable points to are individually immutable, BUT the variable can be pointed to any instance of String you want.

如果您不希望重新分配str指向另一个字符串实例,请最终声明它:

If you don't want it to be possible to reassign str to point to a different string instance, declare it final:

final String str = "Test String";
System.out.println( System.identityHashCode(str) ); // INSTANCE ID of the string

str = str + "Another value"; // BREAKS HORRIBLY

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

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