Note that there are some explanatory texts on larger screens.

plurals
  1. POType-safe varargs method that initialises a Map
    text
    copied!<p>I'm wanting to write a method that I can use to initialise a Map. First cut:</p> <pre><code>Map map(Object ... o) {for (int i = 0; i &lt; o.length; i+=2){result.put(o[i], o[i+1])}} </code></pre> <p>Simple, but not type-safe. Using generics, maybe something like:</p> <pre><code>&lt;TKey, TValue&gt; HashMap&lt;TKey, TValue&gt; map(TKey ... keys, TValue ... values) </code></pre> <p>but that syntax isn't supported. So eventually I come to this:</p> <pre><code>public static &lt;TKey, TValue, TMap extends Map&lt;? super TKey, ? super TValue&gt;&gt; TMap map(TMap map, Pair&lt;? extends TKey, ? extends TValue&gt; ... pairs) { for (Pair&lt;? extends TKey, ? extends TValue&gt; pair: pairs) { map.put(pair.getKey(), pair.getValue()); } return map; } public static &lt;TKey, TValue&gt; HashMap&lt;? super TKey, ? super TValue&gt; map(Pair&lt;? extends TKey, ? extends TValue&gt; ... pairs) { return map(new HashMap&lt;TKey, TValue&gt;(), pairs); } public static &lt;TKey, TValue&gt; Pair&lt;TKey, TValue&gt; pair(TKey key, TValue value) { return new Pair&lt;TKey, TValue&gt;(key, value); } public static final class Pair&lt;TKey, TValue&gt; { private final TKey key; private final TValue value; Pair(TKey key, TValue value) {this.key = key; this.value = value; } public TKey getKey() {return key;} public TValue getValue() {return value;} } </code></pre> <p>But when I try it out, I need to cast it:</p> <pre><code>private static final Map&lt;? extends Class&lt;? extends Serializable&gt;, ? super TypeHandler&lt;? extends Serializable &gt; &gt; validCodeTypes = /* (Map&lt;? extends Class&lt;? extends Serializable&gt;, ? super TypeHandler&lt;? extends Serializable &gt;&gt;) */ map( pair(Integer.class, new IntHandler()), pair(Integer.TYPE, new IntHandler()), pair(Character.class, new CharHandler()), pair(Character.TYPE, new CharHandler()), pair(String.class, new StringHandler()) ); private interface TypeHandler&lt;TType extends Serializable&gt; {} private static class CharHandler implements TypeHandler&lt;Character&gt; {} private static class IntHandler implements TypeHandler&lt;Integer&gt; {} private static class StringHandler implements TypeHandler&lt;String&gt; {} </code></pre> <p>Can anyone tell me how to code my map() methods so that it is entirely general yet doesn't need to be casted?</p>
 

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