09 February 2012

Strange Java syntax (for me at least)

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

1 comment:

علاء الصالحي said...

هذه كمان كانت جديدة علي :)