What are the differences between List
, List<?>
, List<T>
, List<E>
, and List<Object>
?
1. List
List
: is a raw type, therefore not typesafe
. It will only generate a runtime error when the casting is bad. We want a compile time error when the cast is bad. Not recommended to use.
2. List<?>
List<?>
is an unbounded wildcard. But I'm not sure what it's for? I can print a List<?>
without issue:
public static void test(List<?> list){
System.out.println(list); // Works
}
Why can't I add items to a List<?>
?
public static void test(List<?> list){
list.add(new Long(2)); // Error
list.add("2"); // Error
System.out.println(list);
}
3. List<T>
public static void test(List<T> list){ // T cannot be resolved
System.out.println(list);
}
I don't understand this syntax. I saw something like this, and it works:
public <T> T[] toArray(T[] a){
return a;
}
Sometimes, I see <T>
, or <E>
, or <U>
, <T,E>
. Are they all the same or do they represent something different?
4. List<Object>
This gives the error "The method test(List<Object>)
is not applicable for the argument List<String>
":
public static void test(List<Object> list){
System.out.println(list);
}
If I try this then I got "Cannot cast from List<String>
to List<Object>
":
test((List<Object>) names);
I am confused. String
is a subclass of Object
, so why isn't List<String>
a subclass of List<Object>
?
2
. I write some codes to demonstrate this in2
. tyvm – Johannisberger