入门集上的泛型迭代器 [英] Generic Iterator on Entry Set
问题描述
static< V> void myMethod(Map<?,V> map)
{
Iterator< Entry<?,V>> it = map.entrySet()。iterator();
}
我在下面看到编译错误:
类型不匹配:无法从 Iterator< Map.Entry< capture#5-of?,V>>
转换为 Iterator< Map.Entry< ,V>>
迭代< ;?扩展Entry<?,V>> it = map.entrySet()。iterator();
您的尝试失败的原因有点难以理解,特别是因为 Iterator< T>
不会消耗任何 T
(即它没有一个方法需要 T 作为参数)。
您不能指定 Iterator< Entry< V>>
到 Iterator< Entry<?,V>>
,原因与您无法指定 Iterator< Entry
capture#5
只是一个名称,用于区分方法参数中的特定?
和其他不同的通配符实例。它可以很容易成为一个具体的类型。
如果不是 Iterator
你认为像 List
这样的类。
List< Entry< ;整数,字符串>> entries = new ArrayList<>();
//这是一个编译错误,但假设它是可能的
List< Entry<?,String>> wildcardEntries =条目;
//然后,因为这已经是可能的
wilcardEntries.add(new Entry< String,String>(a,b));
条目<整数,字符串> entry1 = entries.get(0);
//这将导致类型错误(ClassCastException)
Integer i = entry1.getKey();
通过使用 I'm seeing below compilation error: Try The reason your attempt doesn't work is a bit hard to see, particularly because You can't assign an The reason this doesn't work is more clear if instead of By using 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:
这篇关于入门集上的泛型迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!?扩展Entry<?,V>
你并没有将自己暴露给这个,因为你并没有声称知道任何有关 Entry 类型的东西
Iterator
可以消耗,只能使用它。
编辑
虽然Jiman删除了他的答案,但他有一个很好的观点,那就是使用for-each循环是一种更简洁的方法(假设您只是试图遍历条目),这将完全避免这个问题。这应该可以工作: $(b
pre $ for(Entry<?,V> entry:map.entrySet()){
/ / ...
}
static <V> void myMethod(Map<?, V> map)
{
Iterator<Entry<?, V>> it = map.entrySet().iterator();
}
Type mismatch: cannot convert from Iterator<Map.Entry<capture#5-of ?,V>>
to Iterator<Map.Entry<?,V>>
Iterator<? extends Entry<?, V>> it = map.entrySet().iterator();
Iterator<T>
does not consume any T
(i.e. it doesn't have a method which takes a T
as a parameter).Iterator<Entry<capture#5-of ?,V>>
to an Iterator<Entry<?, V>>
for the same reason that you can't assign an Iterator<Entry<Integer, String>>
to an Iterator<Entry<?, V>>
. The capture#5
is 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.Iterator
you think of a class like List
.List<Entry<Integer, String>> entries = new ArrayList<>();
//this is a compile error, but assume it is possible
List<Entry<?, String>> wildcardEntries = entries;
//then since this is already possible
wilcardEntries.add(new Entry<String, String>("a", "b"));
Entry<Integer, String> entry1 = entries.get(0);
//this would result in a type error (ClassCastException)
Integer i = entry1.getKey();
? extends Entry<?, V>
you're not exposing yourself to this, as you do not claim to know anything about the type of Entry
your Iterator
can consume, only what it can produce.Edit
for ( Entry<?, V> entry : map.entrySet() ) {
//...
}