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>'
CodePudding user response:
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);
}
CodePudding user response:
The warning is expectable in this situation, because such a casting considered as an unsafe operation. From your example it is hard to say why do you need such a cast, maybe you should re-think your code to avoid it. But if there is no other option, you may leave it, because in runtime it will work. You may also consider to suppress the warning for the method or class:
@SuppressWarnings({"unchecked"})
public static void main(String[] args) {
// your code there
}