Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"new Foo(){}" vs. "new Foo()" in Java

Tags:

java

arraylist

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?

like image 609
marstone Avatar asked Sep 02 '13 18:09

marstone


3 Answers

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.

like image 101
Peter Lawrey Avatar answered Nov 17 '22 00:11

Peter Lawrey


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.

like image 38
nachokk Avatar answered Nov 17 '22 01:11

nachokk


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.

like image 2
Dev Avatar answered Nov 17 '22 01:11

Dev