What is Double Brace initialization in Java?

前端 未结 13 2287
旧时难觅i
旧时难觅i 2020-11-21 07:22

What is Double Brace initialization syntax ({{ ... }}) in Java?

13条回答
  •  不思量自难忘°
    2020-11-21 08:09

    • The first brace creates a new Anonymous Inner Class.
    • The second set of brace creates an instance initializers like static block in Class.

    For example:

       public class TestHashMap {
        public static void main(String[] args) {
            HashMap map = new HashMap(){
            {
                put("1", "ONE");
            }{
                put("2", "TWO");
            }{
                put("3", "THREE");
            }
            };
            Set keySet = map.keySet();
            for (String string : keySet) {
                System.out.println(string+" ->"+map.get(string));
            }
        }
    
    }
    

    How it works

    First brace creates a new Anonymous Inner Class. These inner classes are capable of accessing the behavior of their parent class. So, in our case, we are actually creating a subclass of HashSet class, so this inner class is capable of using put() method.

    And Second set of braces are nothing but instance initializers. If you remind core java concepts then you can easily associate instance initializer blocks with static initializers due to similar brace like struct. Only difference is that static initializer is added with static keyword, and is run only once; no matter how many objects you create.

    more

提交回复
热议问题