List、List<?>、List<T>、List<E>和List<Object>之间的区别 [英] Difference between List, List&lt;?&gt;, List&lt;T&gt;, List&lt;E&gt;, and List&lt;Object&gt;

查看:34
本文介绍了List、List<?>、List<T>、List<E>和List<Object>之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ListListListListList?

What are the differences between List, List<?>, List<T>, List<E>, and List<Object>?

List:是原始类型,因此不是 typesafe.它只会在铸造错误时产生运行时错误.当演员表不好时,我们想要一个编译时错误.不推荐使用.

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.

List 是无界通配符.但我不确定它是做什么用的?我可以毫无问题地打印 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
}

为什么我不能将项目添加到List?

public static void test(List<?> list){
    list.add(new Long(2));     // Error
    list.add("2");             // Error
    System.out.println(list);
}

3.列表

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?

这给出了错误方法test(List)不适用于参数List":

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);
}

如果我尝试这个,那么我得到无法从 List 转换为 List":

If I try this then I got "Cannot cast from List<String> to List<Object>":

test((List<Object>) names);

我很困惑.StringObject 的子类,那么为什么 List 不是 List 的子类??

I am confused. String is a subclass of Object, so why isn't List<String> a subclass of List<Object>?

推荐答案

1) 正确

2) 您可以将其视为只读"列表,您可以在其中不关心项目的类型.可以例如由返回列表长度的方法使用.

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 和 U 是相同的,但人们倾向于使用例如T 代表类型,E 代表元素,V 代表值,K 代表键.编译的方法说它接受了某个类型的数组,并返回了一个相同类型的数组.

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) 你不能把橙子和苹果混在一起.如果您可以将字符串列表传递给需要对象列表的方法,您就可以将一个对象添加到您的字符串列表中.(并不是所有的对象都是字符串)

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)

这篇关于List、List<?>、List<T>、List<E>和List<Object>之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆