Miquel
Miquel

Reputation: 15675

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:

The method get(capture#5-of ? extends Index) in the type Multimap is not applicable for the arguments (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

Upvotes: 2

Views: 617

Answers (3)

Kevin Bourrillion
Kevin Bourrillion

Reputation: 40851

Did you try just using a regular Multimap and Equivalence.wrap-ing your keys?

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691845

The signature of the get method is

get(K key) 

Your Multimap is declared as

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. So passing it an instance of Index is invalid.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1501163

Suppose you put in a 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. 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.)

Upvotes: 2

Related Questions