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?
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.
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