字符串是不可变的(事实)
假设我有两个字符串对象,如下所示:
String str1 = new String("dave");
String str2 = new String("dave");
编译时,会发生字符串对象的实习。根据维基百科,它说“字符串驻留是一种仅存储每个不同字符串值的一个副本的方法,该副本必须是不可变的。Java 中的所有编译时常量字符串都会使用此方法自动驻留。”
如果是这种情况,那么我的两个引用 str1 和 str2 会发生什么情况?编译后他们会指出哪个对象?
我希望这是正确的问题,否则请纠正我,我有点困惑。
最佳答案
下面 str1 和 str2 都是在堆上创建的,因为您是在运行时创建它们。甚至两个对象都是在不同的引用处创建的。
String str1 = new String("dave");
String str2 = new String("dave");
<小时/>Even str1 == str2 will return false. Their values are same but they are two different objects on heap.
但是,如果您在编译时创建对象,例如
String str1="dave";
String str2="dave";
then str1 == str2 will return true, because both these objects are part of same reference created at compile time in string pool.
当我们使用双引号创建字符串时,它首先在字符串池中查找具有相同值的字符串,如果找到它只是返回引用,否则它会在池中创建一个新字符串,然后返回引用。
关于java - String 被嵌入到两个 String 对象中,但行为和值相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904385/