我正试着访问我在我的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");发布于 2013-10-16 04:15:55
当你打电话的时候
HashMap<Product, Integer> hashmap = new HashMap<Product, Integer>();
Iterator<Product> mapIter = hashmap.keySet().iterator();创建的Iterator有空HashMap的视图,因为您还没有向它添加任何内容。当您调用hasNext()时,即使HashMap本身包含元素,Iterator的视图也看不到它。
在您绝对需要时创建Iterator,而不是在此之前。就在您在代码中调用hasNext()之前。
Iterator<Product> mapIter = hashmap.keySet().iterator();
if(!mapIter.hasNext())
System.out.println("Empty mapIter");https://stackoverflow.com/questions/19394944
复制相似问题