How do I address unchecked cast warnings?

后端 未结 23 1206
醉梦人生
醉梦人生 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:35

    Warning suppression is not a solution. You should not be doing two level casting in one statement.

    HashMap getItems(javax.servlet.http.HttpSession session) {
    
        // first, cast the returned Object to generic HashMap
        HashMap theHash = (HashMap)session.getAttribute("attributeKey");
    
        // next, cast every entry of the HashMap to the required type 
        HashMap returingHash = new HashMap<>();
        for (Entry entry : theHash.entrySet()) {
            returingHash.put((String) entry.getKey(), (String) entry.getValue());
        }
        return returingHash;
    }
    

提交回复
热议问题