Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
62 views
in Technique[技术] by (71.8m points)

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

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...