我有一个 Map 类型的对象,我试图用迭代器迭代它。但是编译不通过,代码如下。
// Returned from other method, and the run time type is Map<String, B>
Map<String, ? extends A> map = ...
// Option 1: cannot pass.
Iterator<Map.Entry<String, ? extends A>> iterator = map.entrySet().iterator();
// Option 2: cannot pass either.
// Where B is a subclass extends from A
Iterator<Map.Entry<String, B>> iterator = map.entrySet().iterator();
有人可以帮我吗?谢谢。
最佳答案
我建议你使用foreach循环而不是直接使用Iterator
Map<String, ? extends A> map = new HashMap<>();
for (Map.Entry<String, ? extends A> entry : map.entrySet()) {
String key = entry.getKey();
A value = entry.getValue();
}
关于java - Java 迭代器返回的结果的泛型类型不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35305885/