gpt4 book ai didi

java - 枚举 和 Enumeration

转载 作者:搜寻专家 更新时间:2023-10-30 21:45:44 25 4
gpt4 key购买 nike

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

最佳答案

当您拥有其中之一时,在您可以做什么方面没有实际区别,因为类型参数仅用于“输出”位置。另一方面,在您可以使用它们方面有很大的不同。

假设您有一个 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);
}

更多详细信息,请阅读:

关于java - 枚举<?扩展 ZipEntry> 和 Enumeration<ZipEntry>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/618148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com