为什么我得到两个a1值? [英] Why am I getting two a1 values?
本文介绍了为什么我得到两个a1值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class A
{
private 静态 A a1;
private A(){}
public static 一个createA(){
if (a1 == null)
{
a1 = < span class =code-keyword> new A();
}
System.out.println( a1 = +的哈希码a1.hashCode());
return a1;
}
类 B {
public void m1()
{
A a2 = A.createA();
**强文** System.out.println( a2的哈希码= + a2.hashCode());
}
}
public class Singleton {
public static void main( String [] args){
A.createA();
B b = new B();
b.m1();
}
}
我的尝试:
我尝试在不同的编译器中编译但结果相同。
解决方案
首先A.createA
打印a1
的详细信息。然后你的B.m1
方法调用A.createA
,它会再次打印详细信息。
因为A.createA()
被调用两次:
- 在
main中调用
- 在< code> main b.m1()时>
class A
{
private static A a1;
private A(){}
public static A createA(){
if(a1==null)
{
a1 = new A();
}
System.out.println("hashcode of a1 ="+a1.hashCode());
return a1 ;
}
class B {
public void m1()
{
A a2 = A.createA();
**strong text**System.out.println("hashcode of a2 ="+a2.hashCode());
}
}
public class Singleton {
public static void main(String[] args) {
A.createA();
B b=new B();
b.m1();
}
}
What I have tried:
I have tried compiling in different compilers but same result.
解决方案
FirstlyA.createA
prints the details ofa1
. Then yourB.m1
method callsA.createA
which prints the details a second time.
BecauseA.createA()
is called twice:
- When calling it in
main
- When calling
b.m1() in <code>main
这篇关于为什么我得到两个a1值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文