I have some code which looks something like this (part of a negative test of the method get
):
import java.util.*;
public class Test {
Map<String, Object> map = new HashMap<>();
public static void main (String ... args) {
Test test = new Test();
test.put("test", "value"); // Store a String
System.out.println("Test: " + test.get("test", Double.class)); // Retrieve it as a Double
}
public <T> T get(String key, Class<T> clazz) {
return (T) map.get(key);
}
public void put(String key, Object value) {
map.put(key, value);
}
}
I was expecting it to throw a ClassCastException
but it runs through successfully printing:
Test: value
Why doesn't it throw?
System.out.println
call print? – ThorstenMap
fromObject
to something else, such asString
? Maybe it's allowed due to the polymorphic property ofObject
– DeclarerTest: value
. – Pheontest.get("test", Double.class).doubleValue()
does throw aClassCastException
. – FanionMap<String, String>
– BurroughsClassCastException
when the compiler clearly warns you that the cast is unchecked? – AnnamarieannameseClass<T> clazz
is not doing what you think – Evelynneven