0

I am trying to change return type of implementation with more specific implementation. What am i missing here?

Interface Method

public Collection<Entry<K, ? extends Collection<V>>> entrySet();

Implementing Class Method

public Collection<Entry<K, List<V>>> entrySet(){
    return new ArrayList<>();
}

enter image description here

krishna T
  • 425
  • 4
  • 14

1 Answers1

1

Due to the semantics of the ? extends wildcard. The second generic parameter of Entry is covariant, so Entry<K, List<V>> is indeed a subtype of Entry<K, ? extends Collection<V>>.

However, there is no wildcard for the generic type parameter of Collection, so it is invariant. If we let Dog be Entry<K, List<V>> and let Animal be Entry<K, ? extends Collection<V>>, you will see that this is the classic situation of

Why isn't ArrayList<Dog> a subtype of Collection<Animal>?

Classic Explanation

Collection<Entry<K, List<V>>> simply is not a more specific type than Collection<Entry<K, ? extends Collection<V>>>. They are unrelated.

It will work if you declared it as:

Collection<? extends Entry<K, ? extends Collection<V>>> getEntries();

Note the extra ? extends in the generic type parameter of Collection.

Sweeper
  • 213,210
  • 22
  • 193
  • 313