为什么我得到两个a1值? [英] Why am I getting two a1 values?

查看:93
本文介绍了为什么我得到两个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()被调用两次:



  1. main中调用
  2. 在< 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.

解决方案

Firstly A.createA prints the details of a1. Then your B.m1 method calls A.createA which prints the details a second time.


Because A.createA() is called twice:


  1. When calling it in main
  2. When calling b.m1() in <code>main


这篇关于为什么我得到两个a1值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆