Java Map compiler error with generic

前端 未结 6 2272
孤独总比滥情好
孤独总比滥情好 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:59

    You can use type inference in a helper method, if you want to keep the clean method signature (the client of trimKeyMap shouldn't have to use a generic method):

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

    This is called wildcard capture and is discussed more here: http://www.ibm.com/developerworks/library/j-jtp04298/

提交回复
热议问题