我正在尝试访问我放入 HashMap 中的内容,但它不起作用。 显然 hashmap 的迭代器没有任何东西。它不能执行mapIter.hasNext(),它会是错误的。
代码如下:
Iterator<Product> cIter = getCartContent(cart).iterator();
HashMap<Product, Integer> hash = new HashMap<Product, Integer>();
Iterator<Product> mIter = hash.keySet().iterator();
Product p;
while(cIter.hasNext()) {
p = cIter.next();
if(hash.containsKey(p))
hash.put(p, hash.get(p) + 1);
else
hash.put(p, 1);
}
if(!mIter.hasNext())
System.out.println("Empty mIter");
最佳答案
当你打电话时
HashMap<Product, Integer> hashmap = new HashMap<Product, Integer>();
Iterator<Product> mapIter = hashmap.keySet().iterator();
创建的Iterator
具有空HashMap
的 View ,因为您尚未向其中添加任何内容。当您调用 hasNext()
时,即使 HashMap
本身包含元素,Iterator
的 View 也看不到它。
在您绝对需要时创建迭代器
,而不是之前,即。就在您在代码中调用 hasNext()
之前。
Iterator<Product> mapIter = hashmap.keySet().iterator();
if(!mapIter.hasNext())
System.out.println("Empty mapIter");
关于java - 使用键集/条目集迭代 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19394944/