枚举之间的区别<?扩展ZipEntry>和Enumeration <ZipEntry>?

Epa*_*aga 10 java generics

Enumeration <?之间有区别吗?扩展ZipEntry>和Enumeration <ZipEntry>?如果是这样,有什么区别?

Jon*_*eet 16

当你得到其中一个时,你可以做什么没有实际的区别,因为type参数只用在"输出"位置.另一方面,在你可以作为其中一个使用的方面有很大的不同.

假设你有一个Enumeration<JarEntry>- 你无法将它传递给一个Enumeration<ZipEntry>作为其参数之一的方法.你可以把它传递给一个方法Enumeration<? extends ZipEntry>.

当你有一个在输入和输出位置使用type参数的类型时更有趣 - 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);
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请阅读: