Note that there are some explanatory texts on larger screens.

plurals
  1. POThe type T is not generic; it cannot be parameterized with arguments <?> error in a generic function
    primarykey
    data
    text
    <p>I want to create a generic function that takes any Map &amp; a String key, if the key is not present in the map, then it should create a new instance of the Value Type (which is passed) &amp; put it in the map &amp; then return it.</p> <p>Here is my implementation</p> <pre><code>public &lt;T&gt; T getValueFromMap(Map&lt;String, T&gt; map, String key, Class&lt;T&gt; valueClass){ T value = map.get(key); if (value == null){ try { value = valueClass.newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } map.put(key, value); } return value; } </code></pre> <p>It works if I use it with a normal (not generic) List as the value type, </p> <pre><code>Map&lt;String,List&gt; myMap; List value = getValueFromMap(myMap, "aKey", List.class) //works </code></pre> <p>but not with generic type lists</p> <pre><code>Map&lt;String,List&lt;String&gt;&gt; myMap; List&lt;String&gt; value = getValueFromMap(myMap, "aKey", List.class) //does not work </code></pre> <p>Also if I try to make <code>Map&lt;String, T&gt;</code> map parameter generic by changing it to <code>Map&lt;String, T&lt;?&gt;&gt;</code> it complains that <code>the type T is not generic; it cannot be parameterized with arguments &lt;?&gt;</code></p> <p>Can the generic parameters be themselves made generic?</p> <p>Is there any way to create function with above mentioned requirements?</p> <p>~Update</p> <p>Thanks for all the insightful answers everyone. </p> <p>I have verified that the accepted solution works for any value type with this code</p> <pre><code> Map&lt;String, Map&lt;String, List&lt;String&gt;&gt;&gt; outer = new HashMap&lt;String, Map&lt;String,List&lt;String&gt;&gt;&gt;(); Map&lt;String, List&lt;String&gt;&gt; inner = getValueFromMap(outer, "b", (Class&lt;Map&lt;String, List&lt;String&gt;&gt;&gt;)(Class&lt;?&gt;)HashMap.class); List&lt;String&gt; list = getValueFromMap(inner, "a", (Class&lt;List&lt;String&gt;&gt;)(Class&lt;?&gt;)ArrayList.class); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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