首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Enumeration<之间的区别?扩展了ZipEntry>和Enumeration<ZipEntry>?

Enumeration<之间的区别?扩展了ZipEntry>和Enumeration<ZipEntry>?
EN

Stack Overflow用户
提问于 2009-03-06 09:12:24
回答 3查看 2.4K关注 0票数 10

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-03-06 09:17:20

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

假设你有一个Enumeration<JarEntry> --你不能把它传递给一个以Enumeration<ZipEntry>作为参数的方法。不过,您可以将其传递给一个采用Enumeration<? extends ZipEntry>的方法。

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

代码语言:javascript
复制
// 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);
}

有关更多详细信息,请阅读:

  • The Java language guide to generics
  • The Java generics tutorial (PDF)
  • The Java generics FAQ --特别是the section on wildcards
票数 16
EN

Stack Overflow用户

发布于 2009-03-06 09:18:55

是,直接从其中一个sun generics tutorials

这里的Shape是一个抽象类,有三个子类: Circle、Rectangle和Triangle.

public void draw(列表shape) { for(Shape s: shape) { s.draw(this);}}

值得注意的是,绘图()方法只能在形状列表上调用,而不能在Circle、Rectangle和Triangle列表上调用。为了让该方法接受任何类型的形状,它应该写成如下:

公共空抽签(List<?扩展Shape>形状){ //其余代码相同}

票数 4
EN

Stack Overflow用户

发布于 2009-03-06 09:32:54

现在,您刚刚让我想起了一些我希望在C#世界中拥有的东西。

除了提供的链接之外,在这个问题的答案中还有一些关于C#和Java的很好的链接

其中精选的有:

  • Contravariance and Covariance in C# (代码是特定于C#的,并且是理论上的,因为语法还不存在,但涵盖了来自Sun.

的一般主题

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/618148

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档