Note that there are some explanatory texts on larger screens.

plurals
  1. POGenerics Oddity - I can insert a Long value into a Map<String, String> and it compiles and doesn't fail at runtime
    primarykey
    data
    text
    <p>Give the following code: </p> <pre><code>public static void main(String[] args) { HashMap&lt;String, String&gt; hashMap = new HashMap&lt;&gt;(); HashMap&lt;String, Object&gt; dataMap = new HashMap&lt;&gt;(); dataMap.put("longvalue", 5L); class TestMethodHolder { &lt;T&gt; T getValue(Map&lt;String, Object&gt; dataMap, String value) { return (T)dataMap.get(value); } } hashMap.put("test", new TestMethodHolder().&lt;String&gt;getValue(dataMap, "longvalue")); String value = hashMap.get("test"); // ClassCastException occurs HERE System.out.println(value); } </code></pre> <p>It is not surprising to me that this code compiles, but rather that the ClassCastException occurs on the get line as opposed to the put line above it, though I do have an educated guess as to what what may be occurring. Since generic types are erased during runtime, the cast in getValue() actually never occurs at runtime and is effectively a cast to Object. If the method would be implemented below as follows, then the runtime cast would occur and it would fail on the put line (as expected). Can anyone confirm this?</p> <pre><code>class TestMethodHolder { String getValue(Map&lt;String, Object&gt; dataMap, String value) { return (String)dataMap.get(value); } } </code></pre> <p>Is this a known flaw or oddity of using generics? Is it bad practice then to use the &lt;> notation when calling methods?</p> <p>Edit: I am using the default Oracle JDK 1.7_03.</p> <p>Another implied question from above: Is the cast in the original getValue STILL occurring at runtime but the cast is actually to Object - or is the compiler smart enough to remove this cast from not occurring at runtime at all? This might explain the difference of where the ClassCastException is occurring that people are noticing when running it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload