javahashmapentryset

Why does iterating over entry set not work?


I try to iterate over an EntrySet like this:

 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());
                }
            }
       }

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?


Solution

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

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