简体   繁体   English

无法从Guava MultiMap获取密钥

[英]Unable to get key from a Guava MultiMap

I have the following code: 我有以下代码:

@Override
public boolean putAll(Multimap<? extends Index, ? extends V> multimap) {
    for (Index index : multimap.keySet()) {
        putAll(index, multimap.get(index));
    }
}

Where multimap.get(index) is a compilation error: 其中multimap.get(index)是编译错误:

The method get(capture#5-of ? extends Index) in the type Multimap is not applicable for the arguments (Index) Multimap类型中的get(capture#5-of?extended Index)方法不适用于参数(Index)

Have I stumbled upon a famous generics gotcha? 我是否偶然发现了著名的仿制药陷阱? I don't quiet see what the problem can be. 我不安静地看到问题可能出在哪里。

Side note: I'm building a class that extends SetMultiMap because I have specific key matching requirements 旁注:因为我有特定的键匹配要求,所以我正在构建扩展SetMultiMap的类

Suppose you put in a Multimap<FooIndex, Integer> . 假设您放入了Multimap<FooIndex, Integer> Then you've got: 然后您将获得:

Multimap<FooIndex, Integer> map = ...;
Index plainIndex = ...;
Integer value = map.get(plainIndex);

That's a type failure, because Multimap.get takes a Key . 这是类型错误,因为Multimap.get需要一个Key I suspect you need to make this method generic: 我怀疑您需要使此方法通用:

@Override
public <Key extends Index> boolean putAll(Multimap<Key, ? extends V> multimap) {
    for (Key index : multimap.keySet()) {
        putAll(index, multimap.get(index));
    }
}

(I haven't tested it, but that makes more sense, IMO.) (我还没有测试过,但这更有意义,IMO。)

The signature of the get method is get方法的签名是

get(K key) 

Your Multimap is declared as 您的Multimap声明为

Multimap<? extends Index, ? extends V> multimap

So you don't know the type of the key. 因此,您不知道密钥的类型。 You know that it is or that it extends Index , but you don't know its type. 您知道它是或它扩展了Index ,但您不知道它的类型。 So passing it an instance of Index is invalid. 因此,将其传递给Index实例是无效的。

您是否尝试过仅使用常规的MultimapEquivalence.wrap -ing键?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM