简单分步理解一下new HashMap() {{ }}

new HashMap<Integer, String>() {{ 
	put("0","成功");
}};

第一个花括号应该熟悉,就是一个匿名内部类,那第二个花括号在类里面,只能是一个代码块了。so,以上就是在匿名内部类的代码块里做了一些初始化操作。

public class InitDemo {
    static{
        System.out.println("static block...");
    }
    public InitDemo(){
        System.out.println(this+" constructor...");
    }
    {
        System.out.println(this+" normal block...");
    }
    public static void main(String[] args) {
        new InitDemo();
        System.out.println("**************");
        new InitDemo();
    }
}
#resut:

static block...
init.InitDemo@723279cf normal block...
init.InitDemo@723279cf constructor...
**************
init.InitDemo@10f87f48 normal block...
init.InitDemo@10f87f48 constructor...

其实就是一个静态代码块,构造代码块,构造方法的执行顺序。静态代码是不需要new实例的不能使用this的,而构造代码块是可以使用this的,同构造方法一样。

猜你喜欢

转载自blog.csdn.net/weixin_43275277/article/details/107023844