java - 列表<?> 或列表<对象>

标签 java generics

我有一个方法,其参数应该是“任何东西的列表”。该方法不会修改列表的内容。将此方法定义为更正确吗

void foo(List<?> list) {
}

void foo(List<Object> list) {
}

到底有什么区别?

最佳答案

简短回答,使用 List<?>将允许您接受类似 List<String> 的内容使用 List<Object> 时不会的。

这在官方泛型路径中进行了讨论,herehere .

[...] here is a naive attempt at writing it using generics (and the new for loop syntax):

   void printCollection(Collection<Object> c) {
       for (Object e : c) {
           System.out.println(e);
       }
   }

The problem is that this new version is much less useful than the old one. Whereas the old code could be called with any kind of collection as a parameter, the new code only takes Collection<Object>, which, as we've just demonstrated, is not a supertype of all kinds of collections!
So what is the supertype of all kinds of collections? It's written Collection<?> (pronounced "collection of unknown"), that is, a collection whose element type matches anything. It's called a wildcard type for obvious reasons. We can write:

   void printCollection(Collection<?> c) {
       for (Object e : c) {
           System.out.println(e);
       }
   }

and now, we can call it with any type of collection.

关于java - 列表<?> 或列表<对象>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4244064/

相关文章:

java - 将 neo4j ogm 查询结果映射到 java 对象

java - 如何实现其泛型模板扩展另一个接口(interface)的泛型接口(interface)?

c# - 如何将 Func<T, object> 转换为 Func<dynamic, object>?

c# - 通用列表 FindAll() 与 foreach

java - 如果存在则返回 id 否则插入 postgres

java - 如果 MapStruct 中的源为 null,则将父目​​标设置为 null

java - 使用 SSL 连接的 OpenLdap 失败

java - 减少类型层次结构中的泛型变量的最佳实践?

c# - 简单的一般性误解

java - 如何从小程序打开新的小程序窗口