How do I address unchecked cast warnings?

后端 未结 23 1182
醉梦人生
醉梦人生 2020-11-22 03:06

Eclipse is giving me a warning of the following form:

Type safety: Unchecked cast from Object to HashMap

This is from a call to

23条回答
  •  长情又很酷
    2020-11-22 03:48

    Two ways, one which avoids the tag completely, the other using a naughty but nice utility method.
    The problem is pre-genericised Collections...
    I believe the rule of thumb is: "cast objects one thing at a time" - what this means when trying to use raw classes in a genericised world is that because you don't know what is in this Map (and indeed the JVM might even find that it isn't even a Map!), it obvious when you think about it that you can't cast it. If you had a Map map2 then HashSet keys = (HashSet)map2.keySet() does not give you a warning, despite this being an "act of faith" for the compiler (because it might turn out to be a TreeSet)... but it is only a single act of faith.

    PS to the objection that iterating as in my first way "is boring" and "takes time", the answer is "no pain no gain": a genericised collection is guaranteed to contain Map.Entrys, and nothing else. You have to pay for this guarantee. When using generics systematically this payment, beautifully, takes the form of coding compliance, not machine time!
    One school of thought might say that you should set Eclipse's settings to make such unchecked casts errors, rather than warnings. In that case you would have to use my first way.

    package scratchpad;
    
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Vector;
    
    public class YellowMouse {
    
        // First way
    
        Map getHashMapStudiouslyAvoidingSuppressTag(HttpSession session) {
          Map theHash = (Map)session.getAttribute("attributeKey");
    
          Map yellowMouse = new HashMap();
          for( Map.Entry entry : theHash.entrySet() ){
            yellowMouse.put( (String)entry.getKey(), (String)entry.getValue() );
          }
    
          return yellowMouse;
        }
    
    
        // Second way
    
        Map getHashMapUsingNaughtyButNiceUtilityMethod(HttpSession session) {
          return uncheckedCast( session.getAttribute("attributeKey") );
        }
    
    
        // NB this is a utility method which should be kept in your utility library. If you do that it will
        // be the *only* time in your entire life that you will have to use this particular tag!!
    
        @SuppressWarnings({ "unchecked" })
        public static synchronized  T uncheckedCast(Object obj) {
            return (T) obj;
        }
    
    
    }
    

提交回复
热议问题