【问题标题】:Why does iterating over entry set not work?为什么迭代条目集不起作用?
【发布时间】:2020-09-12 16:41:44
【问题描述】:

我尝试像这样迭代 EntrySet:

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

即使我有那部分 if (list.getKey() == typ1) 我仍然得到印刷案例not implemented case typ1

为什么会这样?我在迭代/ if 案例中做错了什么?

【问题讨论】:

  • typ1list.getKey() 的返回值字符串,还是任何类型的对象?如果是这样,请将它们与 equals() 进行比较,而不是与 '==' 进行比较。

标签: java hashmap entryset


【解决方案1】:

映射(或映射条目)的键是一个对象 - 您需要将其与 equals 进行比较,而不是 ==

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

【讨论】:

    猜你喜欢
    • 2021-08-03
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2023-03-23
    • 2011-05-22
    • 1970-01-01
    相关资源
    最近更新 更多