首页 > 解决方案 > 为什么迭代条目集不起作用?

问题描述

我尝试像这样迭代 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 案例中做错了什么?

标签: javahashmapentryset

解决方案


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

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

推荐阅读