为什么遍历条目集合不起作用?

huangapple go评论87阅读模式
英文:

Why does iterating over entry set not work?

问题

我尝试迭代EntrySet,如下所示:

for (Entry<A, List<B>> list : service.entrySet()) {
    if (list.getKey() == typ1) {
        for (B current : list.getValue()) {                            
            // 做一些操作
        }
    } else {
        PrintHelper.printOut("未实现的情况" + list.getKey());
    }
}

尽管我有这部分 if (list.getKey() == typ1),但我仍然会得到打印出的情况 未实现的情况 typ1

为什么会出现这种情况?我在迭代/条件语句中做错了什么?

英文:

I try to iterate over an EntrySet like this:

 for (Entry&lt;A, List&lt;B&gt;&gt; list : service.entrySet()) {
                if (list.getKey() == typ1) {
                    for (B current : list.getValue()) {                            
                      // do sth
                    }
                }
               
                } else {
                    PrintHelper.printOut(&quot;not implemented case&quot;
                            + list.getKey());
                }
            }
       }

Even though I have that part if (list.getKey() == typ1) I still get the printed case not implemented case typ1.

Why is that the case? What am I doing wrong with the iteration/ the if case?

答案1

得分: 1

一个 Map(或者 map entry)的键是一个对象 - 你需要使用 equals 来进行比较,而不是 ==

if (list.getKey().equals(typ1)) {
英文:

The key of a Map (or map entry) is an object - you need to compare it with equals, not ==:

if (list.getKey().equals(typ1)) {

huangapple
  • 本文由 发表于 2020年9月13日 00:41:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63862606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定