枚举之间有区别吗?扩展ZipEntry>和枚举< ZipEntry>?如果是这样,有什么区别?
解决方法
当您有其中之一时,您可以做什么,因为类型参数仅用于“输出”位置,所以没有实际的区别.另一方面,在您可以使用的其中一个方面有很大的区别.
假设你有枚举< JarEntry> – 你不能把它传给一个采取Enumeration< ZipEntry>作为其论据之一.您可以将其传递给一个采用枚举的方法扩展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);
}
有关详细信息,请阅读:
> The Java language guide to generics
> The Java generics tutorial (PDF)
> The Java generics FAQ – 特别是the section on wildcards
