Iterating over a map entryset

后端 未结 6 970
生来不讨喜
生来不讨喜 2020-12-16 13:37

I need to iterate over the entry set of a map from which I do not know its parameterized types.

When iterating over such entryset, why this does not compile ?

<
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 14:08

    It is because you use the raw type Map, therefore map.entrySet() gets you a non-parametrized Set which in return yields Object on iteration, not Entry.

    A simple, but elegant solution is to use Map, which will still allow you to pass ANY Map, but on the other hand forces map.entrySet() to have a return value of Set:

    public void test(Map map) {        
        for(Entry e : map.entrySet()){
            Object key = e.getKey();
            Object value = e.getValue();
        }       
    }
    

提交回复
热议问题