Java Map compiler error with generic

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

    It might have been possible for the Java 5 expert group, to add a little more power to the specification of wildcards in generic method argument types. I suspect the enhancement didn't make it due to lack of time in the specs phase. See my own recent question here: How does the JLS specify that wildcards cannot be formally used within methods?

    Short of a better solution, you have to make your method a generic method:

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

    You cannot put anything in a Map type, except for the null literal:

    Map map = new HashMap();
    map.put("A", null); // Works
    map.put("B", "X"); // Doesn't work.
    

    The compiler doesn't know that the map's value argument type was String. So it cannot allow you to add anything to the map, even if you got the value from the map itself.

提交回复
热议问题