I've more over 4 years working with Java and today I've seen some piece of code that I thought at first glance it is invalid Java code. The code is: 
List<String> interests = new ArrayList<String>() {{
            add("Java");
            add("C#");
        }};

 

Although, the following code is familiar to me: 
List<String> interests = new ArrayList<String>() {
            @Override
            public void add(int index, String element) {
                // TODO Auto-generated method stub
                super.add(index, element);
            }
        };

 

Here I've defined a reference named "interests" of type "subclass to ArrayList" and I am overriding the "add" method in this subclass. So, I've re-looked at the first snippet again and could realize it to be: 
List<String> interests = new ArrayList<String>() {
        
            // Anonymous initialization block (vs static init block)
            {
                add("Java");
                add("C#");
            }
        };

 

As if I defined a class the following way: 
public class MyClass {

    {
        doSomeThing();
        doSomeThing();
    }

    void doSomeThing() {
        System.out.println("doing");
    }

    public static void main(String[] args) {
        MyClass c = new MyClass();
    }
}

 

Which Prints: 
doing
doing

 

一楼用户回复:这些都是java的新用法

http://m-hewedy.blogspot.com/2012/02/strange-java-syntax-for-me-at-least.html

posted on 2019-07-14 17:34  你不知道的浪漫  阅读(356)  评论(0编辑  收藏  举报