What is Double Brace initialization in Java?

前端 未结 13 2268
旧时难觅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<String,String> map = new HashMap<String,String>(){
            {
                put("1", "ONE");
            }{
                put("2", "TWO");
            }{
                put("3", "THREE");
            }
            };
            Set<String> 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

    0 讨论(0)
提交回复
热议问题