【发布时间】:2013-05-14 01:08:22
【问题描述】:
我在测试字符串创建并检查其哈希码时发现了一个有趣的案例。
在第一种情况下,我使用复制构造函数创建了字符串:
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));
}
}
以上代码的输出为:
S1:816115710 S3:478684581
这是预期的输出,因为实习字符串从字符串池中选择引用,而 s1 选择新对象的引用。所以他们的身份哈希码是不同的。
现在,如果我使用 char 数组创建字符串,那么我会看到一些奇怪的行为:
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));
}
}
以上代码的输出为:
S5:816115710 S6:816115710
这是一个意外的输出。实习字符串和新字符串对象如何具有相同的identityhashcode??
有什么想法吗?
【问题讨论】:
-
@IgorS.:它与我的问题有何关联?
-
"多个对象可以有相同的身份哈希码。这就是哈希码的本质。"
-
@IgorS.:是的,他们只能在某些情况下拥有。在上述情况下,他们不应该有。
-
应该的。为了保持低内存使用 - VM 显然使用延迟加载,因为您没有对指向相同内存地址的字符串做任何事情。第一种情况可能不同,因为字符编码或/和字符串结束字符。