作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
枚举<有区别吗?扩展 ZipEntry> 和 Enumeration
最佳答案
当您拥有其中之一时,在您可以做什么方面没有实际区别,因为类型参数仅用于“输出”位置。另一方面,在您可以使用它们方面有很大的不同。
假设您有一个 Enumeration<JarEntry>
- 你不能把它传递给一个需要 Enumeration<ZipEntry>
的方法作为其论点之一。您可以将它传递给采用 Enumeration<? extends ZipEntry>
的方法虽然。
当你有一个在输入和输出位置都使用类型参数的类型时会更有趣 - List<T>
是最明显的例子。以下是参数变化的三个方法示例。在每种情况下,我们都会尝试从列表中获取一项,然后添加另一项。
// Very strict - only a genuine List<T> will do
public void Foo(List<T> list)
{
T element = list.get(0); // Valid
list.add(element); // Valid
}
// Lax in one way: allows any List that's a List of a type
// derived from T.
public void Foo(List<? extends T> list)
{
T element = list.get(0); // Valid
// Invalid - this could be a list of a different type.
// We don't want to add an Object to a List<String>
list.add(element);
}
// Lax in the other way: allows any List that's a List of a type
// upwards in T's inheritance hierarchy
public void Foo(List<? super T> list)
{
// Invalid - we could be asking a List<Object> for a String.
T element = list.get(0);
// Valid (assuming we get the element from somewhere)
// the list must accept a new element of type T
list.add(element);
}
更多详细信息,请阅读:
关于java - 枚举<?扩展 ZipEntry> 和 Enumeration<ZipEntry>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/618148/
我是一名优秀的程序员,十分优秀!