今天看到这么一段代码,把我给整懵了
private Map<String, User> userDatabase = new HashMap<>() {{List<User> users = List.of( //new User("bob@example.com", "bob123", "Bob", "This is bob."),new User("tom@example.com", "tomcat", "Tom", "This is tom."));users.forEach(user -> {put(user.email, user);});}};
两个{{ }}是什么鬼???
首先我们知道第一个括号是创建匿名类,那么第二个括号是干什么的呢?
看下面这一段代码就明白了
public class Test {static {System.out.println("Static块被调用");}{System.out.println("初始块1被调用");}public Test() {// TODO Auto-generated constructor stubSystem.out.println("构造函数被调用");}{System.out.println("初始块2被调用");hello();}public static void main(String[] args) {System.out.println("==================");new Test();System.out.println("==================");new Test();System.out.println("==================");}private void hello() {System.out.println("hello");}}public class Test {static {System.out.println("Static块被调用");}{System.out.println("初始块1被调用");}public Test() {// TODO Auto-generated constructor stubSystem.out.println("构造函数被调用");}{System.out.println("初始块2被调用");hello();}public static void main(String[] args) {new Test();System.out.println("==================");new Test();}private void hello() {System.out.println("hello");}}
输出
Static块被调用==================初始块1被调用初始块2被调用hello构造函数被调用==================初始块1被调用初始块2被调用hello构造函数被调用==================
第二个大括号就是实例初始化块。
