Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...