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:
public static <T> List<T> newList() {
return new ArrayList<T>();
}
and then do
List<String> test = newList();
This is what Google Collections does.
(And you should almost always be declaring your lists as List
, not as ArrayList
. 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:
import java.util.*;
class GenericDeclarationTest {
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
list1.add("");
String s1 = list1.get(0);
List<String> list2 = new ArrayList();
list2.add("");
String s2 = list2.get(0);
}
}
And here's the generated bytecode (as printed by javap -c GenericDeclarationTest
):
Compiled from "GenericDeclarationTest.java"
class GenericDeclarationTest extends java.lang.Object{
GenericDeclarationTest();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: new #2; //class java/util/ArrayList
3: dup
4: invokespecial #3; //Method java/util/ArrayList."<init>":()V
7: astore_1
8: aload_1
9: ldc #4; //String
11: invokeinterface #5, 2; //InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
16: pop
17: aload_1
18: iconst_0
19: invokeinterface #6, 2; //InterfaceMethod java/util/List.get:(I)Ljava/lang/Object;
24: checkcast #7; //class java/lang/String
27: astore_2
28: new #2; //class java/util/ArrayList
31: dup
32: invokespecial #3; //Method java/util/ArrayList."<init>":()V
35: astore_3
36: aload_3
37: ldc #4; //String
39: invokeinterface #5, 2; //InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
44: pop
45: aload_3
46: iconst_0
47: invokeinterface #6, 2; //InterfaceMethod java/util/List.get:(I)Ljava/lang/Object;
52: checkcast #7; //class java/lang/String
55: astore 4
57: return
}
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:
List<String> test = new ArrayList<>();
// or
Map<String, Object> test2 = new HashMap<>();
Not too hard to type, is it?