Difference between different assignment in generics
What is the difference between
List list = new ArrayList&l开发者_高级运维t;Integer>();
And
List<Integer> list = new ArrayList<Integer>();
By doing:
List list = new ArrayList<Integer>();
you are not telling the compiler what kind of List it is. This would allow someone to compile this code:
String a = (String)list.get(0);
which is clearly wrong and would cause you exception, because you can add anything in the list, so the compiler is not sure if list.get(0) is really an Integer.
Now with this way you are telling the compiler that this list will only accept and hold integers or Integer subclasses (in case it could be subclassed).
List<Integer> list = new ArrayList<Integer>();
so this wouldn't compile:
String b = (String)list.get(0);
In the first case, when you do list.get(i)
, it will return an Object
. In the second case, it will return an Integer
. Think of List<Integer>
as a more specific type of List
(kind of like a subclass in OOP).
The difference is that you don't get any of the benefits of type safety offered by generics when you're using the first declaration -- it's pretty pointless.
Expanding on @Ernest's answer (which is accurate), here are some differences of usage:
List untypedList = new ArrayList<Integer>();
List<Integer> typedList = new ArrayList<Integer>();
// What using the untyped list looks like
for (Object element : untypedList) { // The best we can do is get an Object
Integer i = (Integer)element; // "no-value" code
// do something with i
}
// or, cast to a typed list
for (Integer i : (List<Integer>)untypedList) { // ugly cast
// do something with i
}
// But with a typed list, things are neater (less code = good)
for (Integer i : typedList) {
// do something with i
}
精彩评论