问题
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?
回答1:
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.
回答2:
The second one reduces code clutter, it is new in java 7. But your code should have been
List<Integer> nunbers = new ArrayList<>();
Since you can code to the interface List
, type param of the implementation ArrayList
is inferred.
回答3:
The second one won't compile if the version of your java compiler is inferior than 1.7.
回答4:
The last one is a shortcut that can be used with Java version 7 or newer.
回答5:
They will compile to the exact same code, since Java 7 the second thing is just a shortcut you can use, as it is 100% clear what belongs in the <>
you can left it empty
来源:https://stackoverflow.com/questions/16243541/arraylist-vs-arraylistinteger