Java Map compiler error with generic

前端 未结 6 2271
孤独总比滥情好
孤独总比滥情好 2020-12-19 23:31
// I know that this method will generated duplicate 
// trim keys for the same value but I am just
// trying to understand why we have a compile error:
// The method         


        
6条回答
  •  盖世英雄少女心
    2020-12-19 23:50

    The problem is that the compiler only knows the key type is "unknown", but doesn't know it's the same unknown type for the type of the Map's key and the type returned from get() (even though we as humans realize that it's the same).

    If you want to make it work, you must tell the compiler it's the same unknown type by typing your method, for example:

    void  trimKeyMap(Map map) {
        for (String key : map.keySet()) {
            map.put(StringUtils.trim(key), map.get(key));
        }
    }
    

提交回复
热议问题