Lok*_*esh 5 java memory string
我在使用字符串创建和检查其哈希码进行测试时发现了一个有趣的案例.
在第一种情况下,我使用复制构造函数创建了
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
String s1 = new String("myTestString");
String s3 = s1.intern();
System.out.println("S1: " + System.identityHashCode(s1) + " S3:"
+ System.identityHashCode(s3));
}
}
Run Code Online (Sandbox Code Playgroud)
上述代码的输出是:
S1:816115710 S3:478684581
这是预期的输出,因为实习字符串从字符串池中选择引用,而s1选择新对象的引用.所以他们的身份哈希码是不同的.
现在,如果我使用char数组创建String,那么我会看到一些奇怪的行为:
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
char[] c1 = { 'm', 'y', 'T', 'e', 's', 't', 'S', 't', 'r', 'i', 'n',
'g' };
String s5 = new String(c1);
String s6 = s5.intern();
System.out.println("S5: " + System.identityHashCode(s5) + " S6:"
+ System.identityHashCode(s6));
}
}
Run Code Online (Sandbox Code Playgroud)
上述代码的输出是:
S5:816115710 S6:816115710
这是一个意想不到的输出.interned String和new String对象如何具有相同的identityhashcode?
有任何想法吗?
在第一种情况下,文字在您调用之前myTestString
就已在池中,而在第二种情况下则不是,因此您的 String会直接放入池中。intern
s5
如果我们逐步查看您的示例,则会发生以下情况:
String s1 = new String("myTestString");
=> 使用字符串文字会myTestString
在池中创建一个字符串(我们称之为),并且还会创建一个不在池中的s0
新字符串。s1
String s3 = s1.intern();
=> 检查池中是否存在等效的 String 并找到s0
. 现在s3
和s0
引用同一个实例(即为s3 == s0
true,但是s1 != s0
)。在你的第二个例子中:
String s5 = new String(c1);
创建一个新的字符串,该字符串不在池中String s6 = s5.intern();
检查是否myTestString
在池中但找不到它,因此调用在池中intern
创建一个新的字符串引用s5
,该引用引用与 相同的字符串。事实也是如此s6 == s5
。最后你可以运行这两个程序来确认我的解释(第二个程序打印true
三遍):
public static void main(String[] args) {
String s1 = new String("myTestString");
String s3 = s1.intern();
System.out.println("myTestString" == s1);
System.out.println(s3 == s1);
System.out.println("myTestString" == s3);
}
public static void main(String[] args) {
String s1 = new String(new char[] {'m', 'y', 'T', 'e', 's', 't', 'S', 't', 'r', 'i', 'n', 'g'});
String s3 = s1.intern();
System.out.println("myTestString" == s3);
System.out.println("myTestString" == s1);
System.out.println(s3 == s1);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
102 次 |
最近记录: |