Difference between List, List<?>, List<T>, List<E>, and List<Object>

Thang Pham picture Thang Pham · Jun 3, 2011 · Viewed 156k times · Source

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

Answer

Kaj picture Kaj · Jun 3, 2011

1) Correct

2) You can think of that one as "read only" list, where you don't care about the type of the items.Could e.g. be used by a method that is returning the length of the list.

3) T, E and U are the same, but people tend to use e.g. T for type, E for Element, V for value and K for key. The method that compiles says that it took an array of a certain type, and returns an array of the same type.

4) You can't mix oranges and apples. You would be able to add an Object to your String list if you could pass a string list to a method that expects object lists. (And not all objects are strings)