枚举之间的差异<?扩展ZipEntry&gt;和枚举&lt; ZipEntry&gt;? [英] Difference between Enumeration&lt;? extends ZipEntry&gt; and Enumeration&lt;ZipEntry&gt;?

查看:93
本文介绍了枚举之间的差异<?扩展ZipEntry&gt;和枚举&lt; ZipEntry&gt;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

枚举<?>有区别吗?扩展ZipEntry>和枚举< ZipEntry>?如果是这样,有什么区别?

解决方案

没有实际的区别,你可以做什么,当你有一个因为类型参数仅用于输出位置。另一方面,你可以使用作为其中之一。



假设你有一个 Enumeration< JarEntry> - 你不能将它传递给一个将 Enumeration< ZipEntry> 作为其参数之一的方法。您可以 将它传递给采用 Enumeration <?>的方法。但是扩展ZipEntry>



当你有一个在输入和输出位置都使用type参数的类型时, code> List< T> 是最明显的例子。以下是三个参数变化的方法示例。在每种情况下,我们都会尝试从列表中获取一个项目,然后再添加一个项目。

  //非常严格 - 仅限真正的List< T>将做
public void Foo(List< T> list)
{
T element = list.get(0); //有效
list.add(element); //有效的
}

// Lax以一种方式:允许任何List类型的
//从T派生
public void Foo List< ;? extends T> list)
{
T element = list.get(0); //有效
//无效 - 这可能是一个不同类型的列表。
//我们不想将对象添加到列表中< String>
list.add(element);
}

// Lax以其他方式:允许任何List类型为
的列表//在T的继承层次结构中向上
public void Foo(List< ;?super T>列表)
{
//无效 - 我们可能会要求List< Object>为一个字符串。
T element = list.get(0);
//有效(假设我们从某处获取元素)
//列表必须接受一个T
list.add(element)类型的新元素;
}

有关更多详情,请阅读:


Is there a difference between Enumeration<? extends ZipEntry> and Enumeration<ZipEntry>? If so, what is the difference?

解决方案

There's no practical difference in terms of what you can do when you've got one of them, because the type parameter is only used in an "output" position. On the other hand, there's a big difference in terms of what you can use as one of them.

Suppose you had an Enumeration<JarEntry> - you couldn't pass this to a method which took Enumeration<ZipEntry> as one of its arguments. You could pass it to a method taking Enumeration<? extends ZipEntry> though.

It's more interesting when you've got a type which uses the type parameter in both input and output positions - List<T> being the most obvious example. Here are three examples of methods with variations on a parameter. In each case we'll try to get an item from the list, and add another one.

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

For more details, read:

这篇关于枚举之间的差异<?扩展ZipEntry&gt;和枚举&lt; ZipEntry&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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