我正在通过教程学习Singleton设计模式。基本上,据我了解,它可以确保只创建一个类的一个实例,并且与该类的任何交互都是通过堆中的那个实例完成的。这么说,我在SingletonPatternDemo.java中写道:
SingleObject object1 = SingleObject.getInstance();
SingleObject object2 = SingleObject.getInstance();
根据我的理解,object1和object2都引用相同的对象,因此它们应指向内存中的相同位置。
但是当我写的时候:
System.out.println("object1 HashCode: " + System.identityHashCode(System.identityHashCode(object1)));
System.out.println("object2 HashCode: " + System.identityHashCode(System.identityHashCode(object2)));
运行它后,我得到:
object1 HashCode: 865113938
object2 HashCode: 1442407170
因为这两个对象引用了相同的实例,所以它们不应该返回相同的哈希码吗?还是我错过了什么?
答案 0 :(得分:3)
System.identityHashCode(System.identityHashCode(object1))
内部System.identityHashCode(object1)
将返回int
,它是object1
的哈希码。
外部调用需要使用Object
-int
是boxed到Integer
。由于它位于cached range之外,因此创建了Integer
对象。为其显示哈希代码的Integer
。
System.identityHashCode(System.identityHashCode(object2))
此处,内部调用将返回int
-与object1
相同。 但是,如上所述,当您致电System.identityHashCode
时,int
被装在Integer
上,与上述实例不同。
通过说明方式:
public static void main(final String[] args) {
final String hello = "Hello World";
System.out.println(System.identityHashCode(hello));
System.out.println(System.identityHashCode(hello));
System.out.println(System.identityHashCode(System.identityHashCode(hello)));
System.out.println(System.identityHashCode(System.identityHashCode(hello)));
}
输出:
//前两个相同
899644639
899644639
//第二两个不同
530737374
1332668132