Possible Duplicate:
Java Generics: Cannot cast List<SubClass> to List<SuperClass>?
I want to create function on some base class, that create it inheritance classes.
I have try this:
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
}
}
And this:
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;
}
}
But when I try to cast the array I receive an error. This is my code:
String[] txts = ...; // Some texts
ArrayList<FooFormat> list = (ArrayList<FooFormat>) BaseFormat.getTextFormat(txts); // Casting ERROR
So how can I do it, but still keep it generic?