重複の可能性:
Javaジェネリック:List<SubClass>をList<SuperClass>にキャストできませんか?
継承クラスを作成するいくつかの基本クラスに関数を作成したいと思います。
私はこれを試しました:
class BaseFormat
{
// Some variables
public BaseFormat(string txt)
{
// Do something
}
public static <T> ArrayList<T extends BaseFormat> getTextFormat(String[] txt)
{
ArrayList<T> list = new ArrayList<T>();
for (int i = 0; i < txt.length; i++)
{
list.add(new T(txt[i])); // ERROR
}
return list;
}
}
class FooFormat extends BaseFormat
{
// Some variables
public FooFormat (string txt)
{
// Do something
}
}
この:
class BaseFormat
{
// Some variables
public BaseFormat(string txt)
{
// Do something
}
public static ArrayList<BaseFormat> getTextFormat(String[] txt)
{
ArrayList<T> list = new ArrayList<T>();
for (int i = 0; i < txt.length; i++)
{
list.add(new BaseFormat(txt[i]));
}
return list;
}
}
しかし、配列をキャストしようとすると、エラーが発生します。これは私のコードです:
String[] txts = ...; // Some texts
ArrayList<FooFormat> list = (ArrayList<FooFormat>) BaseFormat.getTextFormat(txts); // Casting ERROR
では、どうすればそれを実行できますが、それでも汎用性を維持できますか?