Search code examples
javaobjecthashmap

Convert "Object" to "HashMap" in Java


Here is a example:

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        HashMap<Integer, Integer> a = new HashMap<Integer, Integer>();
        a.put(1,2);
        a.put(2,5);
        Object b = a;
        // Do something here to make the variable "b" become a HashMap
    }
}

I tried this

HashMap<Integer, Integer> c = (HashMap<Integer, Integer>) b;

I get this warning:

Unchecked cast: 'java.lang.Object' to 'java.util.HashMap<java.lang.Integer,java.lang.Integer>'


Solution

  • Don’t use @SuppressWarnings. That warning exists for good reason: all sorts of strange things can go wrong, if you try to force the compiler to make an unsafe assumption about a generically typed object. For example:

    Map<Integer, Integer> a = Map.of(1, 2, 3, 4);
    
    Object obj = a;
    
    // Compiler warning:  unchecked cast
    Map<String, String> b = (Map<String, String>) obj;
    
    // Causes ClassCastException, even though the code has no obvious cast!
    String key = b.get(1);
    

    The safe way to do this is to immediately verify that the object is a Map that contains Integer keys and values:

    Map<Integer, Integer> a = Map.of(1, 2, 3, 4);
    
    Object obj = a;
    
    // This is safe, because it doesn't make any assumptions about generic typing.
    Map<?, ?> b = (Map<?, ?>) obj;
    
    Map<Integer, Integer> c = new HashMap<>();
    for (Map.Entry<?, ?> entry : b.entrySet()) {
        // Throws a ClassCastException right away, instead of later
        // in an unexpected and strange place.
        Integer key = (Integer) entry.getKey();
        Integer value = (Integer) entry.getValue();
    
        c.put(key, value);
    }