Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList<> vs ArrayList<Integer>

What is the difference in the two following declarations of an ArrayList?

ArrayList<Integer> nunbers = new ArrayList<Integer>();

vs

ArrayList<Integer> nunbers = new ArrayList<>();

Is one of them preferred over the other?

like image 712
PalSivertsen Avatar asked Apr 26 '13 19:04

PalSivertsen


1 Answers

The second one has its type parameter inferred, which is a new thing in Java 7. <> is called "the diamond".

Also note that type inference itself is not new in Java, but the ability to infer it for the generic class being instantiated is new.

Compilers from releases prior to Java SE 7 are able to infer the actual type parameters of generic constructors, similar to generic methods. However, compilers in Java SE 7 and later can infer the actual type parameters of the generic class being instantiated if you use the diamond (<>).

I'd say the second one is probably preferred as long as you can make sure the code only needs to run on Java 7, since it is clearer, and only reduces redundant information.

like image 164
zw324 Avatar answered Sep 25 '22 02:09

zw324