gpt4 book ai didi

java - 泛型:实例化类型为 >

转载 作者:行者123 更新时间:2023-11-29 03:54:48 25 4
gpt4 key购买 nike

在下面的代码中,我想从 Map 中获取一个“?super SomeInterface”,我该如何声明“值”的类型才能做到这一点?

class SomeClass { /* override hashCode & equals appropriately */}
interface SomeInterface<T> { }
interface AnotherInterface { }


class MainClass {
private final Map<SomeClass, ? super SomeInterface<? extends AnotherInterface>> someMap;
private final SomeClass someClass = new SomeClass();

public MainClass() {
someMap = new HashMap<SomeClass, SomeInterface<? extends AnotherInterface>>();
someMap.put(someClass, new SomeInterface<AnotherInterface>(){});
}

private void getValue(SomeClass someClass) {
/*
* I want to get a "? super SomeInterface<? extends AnotherInterface>" from the Map
* how do I declare the type of "value" to enable me to do so
*
*/
Object value = someMap.get(someClass);
}

private
<T extends SomeInterface<? extends AnotherInterface>>
T getValue2(SomeClass someClass) {
T value;
// the code below does not work
// Type mismatch: cannot convert from capture#3-of
// ? super SomeInterface<? extends AnotherInterface> to T
value = someMap.get(someClass);
}
}

提前致谢。

最佳答案

Object是你唯一可以申报的东西 value因为,如果你有一个 ? super Anything它可以是 Anything 的任何父类(super class)一直到对象。因此,您必须将其分配给最通用的类​​型。

如果您有一个产生 <? super Something> 的通用类型这几乎可以肯定是一个糟糕的设计(我什至不认为该语言支持它)。那是因为你不能对它产生的东西进行任何推论,而且几乎总是一无所获(不过,请参阅下面我就该主题提出的问题)。 “PECS”是一个很好的助记符:“生产:(使用)扩展,消费:(使用) super ”。

另见

关于java - 泛型:实例化类型为 <? super someClass, AnotherClass<?扩展 YetAnotherClass>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6962151/

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