首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >迭代hashmap,使用keyset/entryset

迭代hashmap,使用keyset/entryset
EN

Stack Overflow用户
提问于 2013-10-16 03:53:51
回答 1查看 1.3K关注 0票数 0

我正试着访问我在我的hashmap中放的东西,但它不起作用。显然,hashmap的迭代器没有任何内容。它不能执行mapIter.hasNext(),它将是假的。

下面是代码:

代码语言:javascript
复制
    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");
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-16 04:15:55

当你打电话的时候

代码语言:javascript
复制
HashMap<Product, Integer> hashmap = new HashMap<Product, Integer>();
Iterator<Product> mapIter = hashmap.keySet().iterator();

创建的Iterator有空HashMap的视图,因为您还没有向它添加任何内容。当您调用hasNext()时,即使HashMap本身包含元素,Iterator的视图也看不到它。

在您绝对需要时创建Iterator,而不是在此之前。就在您在代码中调用hasNext()之前。

代码语言:javascript
复制
Iterator<Product> mapIter = hashmap.keySet().iterator();

if(!mapIter.hasNext())
    System.out.println("Empty mapIter");
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19394944

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档