Casting from Object in Java without getting an unchecked warning
casting, generics, java
Solution
Edited (based on question clarification)
Casting to `HashMap<String, Integer>` (btw, using `Map` instead of `HashMap` is arguably a better choice) is a different story. There's sadly no way to avoid an unchecked warning in that case due to type erasure. You can, however, use it as non-generic map:
if (foo instanceof Map) {
((Map) foo).put("a", 5);
}
You'll obviously have to cast on "gets" and you lose (perceived) type safety but there'll be no unchecked warning.
There must be more to this story. The following code:
Map<String, Object> map = Maps.newHashMap(); // or new HashMap<String, Object>();
Object foo = map.get("bar");
if (foo instanceof Widget) {
((Widget) foo).spin();
}
does NOT generate an unchecked warning for me. Nor can I imagine why would it. If you know beforehand that "bar" would always return a widget, doing this:
Widget widget = (Widget) map.get("bar");
widget.spin();
would work perfectly fine as well. Am I missing something here?
Problem
I wrote a class that has a map of `<String, Object>`. I need it to hold arbitrary objects, but at the same time sometimes I need to cast some of those objects, so I'll do something like ``` HashMap<String, Object> map = new HashMap<String, Object>(); Object foo = map.get("bar"); if (foo instanceof HashMap) { ((HashMap<String, Integer>) foo).put("a", 5); } ``` which gives the warning ``` Stuff.java:10: warning: [unchecked] unchecked cast found : java.lang.Object required: java.util.HashMap<java.lang.String,java.lang.Integer> ((HashMap<String, Integer>) foo).put("a", 5); ``` I suspect it has to do with the use of generics. I can get rid of the error using @SupressWarnings("unchecked"), but I was wondering if there was a better way to do it. Or maybe the fact that I'm getting the warning means I should reconsider what I'm doing. Is there anything I could do, or should I just use @SupressWarnings?