Map の初期化に使用できるメソッドを書きたいと思っています。最初のカット:
Map map(Object ... o) {for (int i = 0; i < o.length; i+=2){result.put(o[i], o[i+1])}}
シンプルですが、型安全ではありません。ジェネリックを使用すると、おそらく次のようになります。
<TKey, TValue> HashMap<TKey, TValue> map(TKey ... keys, TValue ... values)
しかし、その構文はサポートされていません。だから最終的に私はこれに行きます:
public static <TKey, TValue, TMap extends Map<? super TKey, ? super TValue>> TMap map(TMap map, Pair<? extends TKey, ? extends TValue> ... pairs) {
for (Pair<? extends TKey, ? extends TValue> pair: pairs) {
map.put(pair.getKey(), pair.getValue());
}
return map;
}
public static <TKey, TValue> HashMap<? super TKey, ? super TValue> map(Pair<? extends TKey, ? extends TValue> ... pairs) {
return map(new HashMap<TKey, TValue>(), pairs);
}
public static <TKey, TValue> Pair<TKey, TValue> pair(TKey key, TValue value) {
return new Pair<TKey, TValue>(key, value);
}
public static final class Pair<TKey, TValue> {
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;}
}
しかし、試してみると、キャストする必要があります。
private static final Map<? extends Class<? extends Serializable>, ? super TypeHandler<? extends Serializable > > validCodeTypes =
/* (Map<? extends Class<? extends Serializable>, ? super TypeHandler<? extends Serializable >>) */
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<TType extends Serializable> {}
private static class CharHandler implements TypeHandler<Character> {}
private static class IntHandler implements TypeHandler<Integer> {}
private static class StringHandler implements TypeHandler<String> {}
完全に一般的でありながらキャストする必要がないように、 map() メソッドをコーディングする方法を誰か教えてもらえますか?