static <V> void myMethod(Map<?, V> map)
{
Iterator<Entry<?, V>> it = map.entrySet().iterator();
}
I’m seeing below compilation error:
Type mismatch: cannot convert from Iterator<Map.Entry<capture#5-of ?,V>> to Iterator<Map.Entry<?,V>>
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Try
The reason your attempt doesn’t work is a bit hard to see, particularly because
Iterator<T>does not consume anyT(i.e. it doesn’t have a method which takes aTas a parameter).You can’t assign an
Iterator<Entry<capture#5-of ?,V>>to anIterator<Entry<?, V>>for the same reason that you can’t assign anIterator<Entry<Integer, String>>to anIterator<Entry<?, V>>. Thecapture#5is just a name used to differentiate the specific?found in your method’s parameter from other distinct wildcard instances. It could just as easily be a concrete type.The reason this doesn’t work is more clear if instead of
Iteratoryou think of a class likeList.By using
? extends Entry<?, V>you’re not exposing yourself to this, as you do not claim to know anything about the type ofEntryyourIteratorcan consume, only what it can produce.Edit
Though Jiman deleted his answer, he had a good point that using the for-each loop is a lot cleaner approach (assuming you’re just trying to iterate over the entries) that would avoid this issue entirely. This should work: