Incompatible generic wildcard captures

前端 未结 2 1532
情深已故
情深已故 2021-01-14 18:01

in the following snippet:

package test;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

public class WildcardsTest

        
相关标签:
2条回答
  • 2021-01-14 18:31

    Do it like this and it will work:

    private final Iterator<? extends
        Map.Entry<K, ? extends Collection<V>>
    > iterator;
    

    You can still use the iterator like this:

    public void foo(){
        while(iterator.hasNext()){
            Entry<K, ? extends Collection<V>> entry = iterator.next();
            Collection<V> value = entry.getValue();
        }
    }
    

    For reference, read the get and put principle (originally from Java Generics and Collections)

    0 讨论(0)
  • 2021-01-14 18:51

    The assignment is incorrect, although the types seem to match exactly.

    The two ?-wildcards can be bound to two different classes. Put it this way, it is quite obvious that there is a type mismatch:

    private Iterator<Map.Entry<K, ArrayList<V>>> iterator;
    public WildcardsTest(Map<K, HashSet<V>> map) {
        iterator = map.entrySet().iterator();
    }
    

    When you introduce the C, you "force them" to refer to the same class.

    0 讨论(0)
提交回复
热议问题