我有一个方法,其参数应该是“任何东西的列表”。该方法不会修改列表的内容。将此方法定义为更正确吗
void foo(List<?> list) {
}
或
void foo(List<Object> list) {
}
到底有什么区别?
最佳答案
简短回答,使用 List<?>
将允许您接受类似 List<String>
的内容使用 List<Object>
时不会的。
[...] 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 writtenCollection<?>
(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/