与えられた:
Object nestKey;
Object nestedKey;
Object nestedValue;
Map<T,Map<T,T>> nest;
Map<T,T> nested;
ネストされた場所にマッピングを追加するにはどうすればよいですか。
nest.containsKey(nestKey)== true;
?
それとも、より効果的なコレクションの既存のライブラリがありますか?
与えられた:
Object nestKey;
Object nestedKey;
Object nestedValue;
Map<T,Map<T,T>> nest;
Map<T,T> nested;
ネストされた場所にマッピングを追加するにはどうすればよいですか。
nest.containsKey(nestKey)== true;
?
それとも、より効果的なコレクションの既存のライブラリがありますか?
これは、次のいずれかのかなり一般的なイディオムです。
次のジェネリックメソッドのようなものですか?
static <U,V,W> W putNestedEntry(
Map<U,Map<V,W>> nest,
U nestKey,
V nestedKey,
W nestedValue)
{
Map<V,W> nested = nest.get(nestKey);
if (nested == null)
{
nested = new HashMap<V,W>();
nest.put(nestKey, nested);
}
return nested.put(nestedKey, nestedValue);
}
よく分からない。次のようにネストされたマップに追加したいと思います。
nest.get(nestKey).put(nestedKey, nestedValue);
get on outer map が type のマップを返すため、これは不可能Map<?, ?>
です。put メソッドを呼び出すことはできません。無制限のワイルドカード「?」コレクションのコンテンツのタイプがわからないが、それらをオブジェクトと見なしたい場合に使用する必要があります。コンテンツを読み取って変更する必要があり、マップに異種オブジェクトが含まれている場合は、生の型を使用できます。それは次のようなものです:
Map<?, Map> nest;
もちろん、最善の方法は (可能であれば) 同種の Map を使用してその型を指定することです。例えば。Map<String, String>
これを試して
if (nest.containsKey(nestKey)) { ((Map) nest.get(nestKey)).put(nestedKey, nestedValue); }