java - 使用键集/条目集迭代 HashMap

标签 java iterator hashmap

我正在尝试访问我放入 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/

相关文章:

java - 将参数从 .txt 文件传递​​到 web.xml

python - 是文件对象迭代器 "broken?"

Rust 实现迭代器

c++ - 如何解决有关迭代器构造函数的一系列错误,涉及预期左值、缺少转换和可行性

java - 压缩要通过 RMI 发送的 Java HashMap

java - Eclipse 说无法解析类的静态字段

来自 imageView 的 Java Fx 图像更新

java - Windows 上的 Sqlite db - 小型 java 应用程序

java - HashMap 如何保存和查找键

java-无法将查询返回的对象映射到正确定义的类