ジェネリックでこれを行う適切な方法がわかりません。Foo
ジェネリック ( ) を持つクラスがありFoo<class>
ます。次に、のマップが必要ですMap<String, Foo>
。Foo<String>
これで、 1 つのマップ アイテムとして追加したり、別のマップ アイテムとして追加したりできますFoo<Integer>
。ただし、マップの get メソッドを使用すると、単にFoo
back を取得し、型を推測できなくなるため、次のようにします。
String s = map.get("StringFoo")
コンパイルエラーが発生したため、次のことを行う必要があります。
文字列 s = (文字列) map.get("StringFoo")
キャストを回避するためにこのようなことを行うための良いパターンは何ですか。そもそもそれがジェネリックの目的であるためです。のようなことができるかもしれませんがMap<String, Foo<?>>
、その方法はありますか?
私のコードの詳細は次のとおりです。これはディレクトリに配置してjavac *.java && java Main
実行できます。
Foo.java にジェネリック Java クラスがあります。
public class Foo<T>
{
T value;
public T getValue()
{
return this.value;
}
public void setValue(T t)
{
this.value = t;
}
}
今、Main.java に次のテスト クラスがあります。
import java.util.Map;
import java.util.HashMap;
public class Main
{
public static void main(String[] a)
{
Foo<String> fooStr = new Foo<String>();
fooStr.setValue("TEST 123");
Foo<Integer> fooInt = new Foo<Integer>();
fooInt.setValue(314159);
Map<String, Foo> mapOfFoo = new HashMap<String, Foo>();
mapOfFoo.put("Strings", fooStr);
mapOfFoo.put("Integer", fooInt);
System.out.println("All set");
String s = mapOfFoo.get("Strings").getValue();
System.out.println("Got: " + s);
}
}
これをコンパイルすると、次のエラーが発生します。
Main.java:21: error: incompatible types
String s = mapOfFoo.get("Strings").getValue();
^
required: String
found: Object
1 error
Main.java でこれを行うと、次のように動作します。
import java.util.Map;
import java.util.HashMap;
public class Main
{
public static void main(String[] a)
{
Foo<String> fooStr = new Foo<String>();
fooStr.setValue("TEST 123");
Foo<Integer> fooInt = new Foo<Integer>();
fooInt.setValue(314159);
Map<String, Foo> mapOfFoo = new HashMap<String, Foo>();
mapOfFoo.put("Strings", fooStr);
mapOfFoo.put("Integer", fooInt);
System.out.println("All set");
String s = (String)mapOfFoo.get("Strings").getValue();
System.out.println("Got: " + s);
}
}
このようなもののベストプラクティスが何であるかはわかりません。誰か提案はありますか?