Enumeration<之间有区别吗?扩展ZipEntry>和枚举?如果是这样,有什么不同?
发布于 2009-03-06 09:17:20
当你得到其中一个的时候,你能做什么并没有什么实际的区别,因为type参数只用在"output“位置。另一方面,在你可以作为其中之一使用方面有很大的不同。
假设你有一个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);
}有关更多详细信息,请阅读:
发布于 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>形状){ //其余代码相同}
发布于 2009-03-06 09:32:54
现在,您刚刚让我想起了一些我希望在C#世界中拥有的东西。
除了提供的链接之外,在这个问题的答案中还有一些关于C#和Java的很好的链接
其中精选的有:
的一般主题
https://stackoverflow.com/questions/618148
复制相似问题