When initialising an instance of a Generic class in Java is there any benefit to specifying the Type on both sides of the statement?
Or to put it another way, what’s the difference between these two valid statements:
ArrayList<String> test = new ArrayList<String>();
and:
ArrayList<String> test = new ArrayList();
(It seems second statement is not equivalent to:
ArrayList<String> test = new ArrayList<Object>();
as the third statement in invalid and causes an incompatible types compile error.)
The second statement winds up being more or less equivalent to the first, but only because generics are erased at runtime. You’ll get an ‘unchecked conversion’ warning, which is why I don’t like it.
A better way is to have a static generic method like this:
and then do
This is what Google Collections does.
(And you should almost always be declaring your lists as
List, not asArrayList. Makes it easy to switch the implementation later.)Edit: dribeas asked in the comments what the exact difference is between the two declarations, and why I said they are ‘more or less equivalent’. Because of type erasure, the only difference between them is the warning. Here’s a small piece of code comparing them:
And here’s the generated bytecode (as printed by
javap -c GenericDeclarationTest):As you can see (if you have the patience), the two are identical.
Incidentally, this may become easier in Java 7. There is a proposal in Project Coin for ‘Improved Type Inference for Generic Instance Creation’. If it makes the final cut, the syntax will be:
Not too hard to type, is it?