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?
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.
You are anonymously instantiating a class. You could override methods in the later case without the need to define a new class in an own file.
o3
is still an instance of an anonymous subclass of ArrayList
which has an empty instance initialization block (the inner {}
).
// Instantiate an object of type `ArrayList<String>`
Object o1 = new ArrayList<String>();
// Instantiate an anonymous subclass of `ArrayList<String>`
Object o2 = new ArrayList<String>(){};
// Instantiate an anonymous subclass of `ArrayList<String>` with an empty initializer block
Object o3 = new ArrayList<String>(){{}};
Object o2 = new ArrayList<String>(){};
it is annonymous inner class that extends ArrayList
class and overrides nothing.
Object o2 = new ArrayList<String>(){{}};
it is also annonymous inner class that extends ArrayList
class and overrides nothing but has a empty instance block
.