For example:
Object o1 = new ArrayList<String>();
Object o2 = new ArrayList<String>(){};
Object o3 = new ArrayList<String>(){{}};
What's the difference?
I can't google out the 2nd/3rd grammar of Java, any reference?
The first creates an ArrayList
The second creates an anonymous subclass of ArrayList which has a specific generic type of String
The third is the same but it has a initializer block which is empty.
Note: Where ever possible, you should write the simplest and clearest code you can, esp if you are thinking about performance.
Object o1 = new ArrayList<String>();
Creates an ArrayList.
Object o2 = new ArrayList<String>(){};
Here you are creating an anonymous class that extends ArrayList<String>
and don't override anything. So the difference it's that you are subclassing an ArrayList without overrding behaviour, never do this if you don't have a good reason.
Object o3 = new ArrayList<String>(){{}};
You are creating the same as 2 but with an empty initalizer block.
Object o1 = new ArrayList<String>();
Creating a new ArrayList object and assigning it to o1
Object o2 = new ArrayList<String>(){};
Creating a new instance of an anonymous class that extends ArrayList and assigning it to o2
Object o3 = new ArrayList<String>(){{}};
Creating a new instance of a (different from o2
) anonymous class that extends ArrayList that has a no-op instance initializer.
Functionally the anon classes assigned to o2
and o3
are equivalent but technically they will be different classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With