今天看到这么一段代码,把我给整懵了

    1. private Map<String, User> userDatabase = new HashMap<>() {
    2. {
    3. List<User> users = List.of( //
    4. new User("bob@example.com", "bob123", "Bob", "This is bob."),
    5. new User("tom@example.com", "tomcat", "Tom", "This is tom."));
    6. users.forEach(user -> {
    7. put(user.email, user);
    8. });
    9. }
    10. };

    两个{{ }}是什么鬼???
    首先我们知道第一个括号是创建匿名类,那么第二个括号是干什么的呢?
    看下面这一段代码就明白了

    1. public class Test {
    2. static {
    3. System.out.println("Static块被调用");
    4. }
    5. {
    6. System.out.println("初始块1被调用");
    7. }
    8. public Test() {
    9. // TODO Auto-generated constructor stub
    10. System.out.println("构造函数被调用");
    11. }
    12. {
    13. System.out.println("初始块2被调用");
    14. hello();
    15. }
    16. public static void main(String[] args) {
    17. System.out.println("==================");
    18. new Test();
    19. System.out.println("==================");
    20. new Test();
    21. System.out.println("==================");
    22. }
    23. private void hello() {
    24. System.out.println("hello");
    25. }
    26. }
    27. public class Test {
    28. static {
    29. System.out.println("Static块被调用");
    30. }
    31. {
    32. System.out.println("初始块1被调用");
    33. }
    34. public Test() {
    35. // TODO Auto-generated constructor stub
    36. System.out.println("构造函数被调用");
    37. }
    38. {
    39. System.out.println("初始块2被调用");
    40. hello();
    41. }
    42. public static void main(String[] args) {
    43. new Test();
    44. System.out.println("==================");
    45. new Test();
    46. }
    47. private void hello() {
    48. System.out.println("hello");
    49. }
    50. }

    输出

    1. Static块被调用
    2. ==================
    3. 初始块1被调用
    4. 初始块2被调用
    5. hello
    6. 构造函数被调用
    7. ==================
    8. 初始块1被调用
    9. 初始块2被调用
    10. hello
    11. 构造函数被调用
    12. ==================

    第二个大括号就是实例初始化块。