不确定标题是否有意义,我会尽力解释。我有一个扩展 ArrayList 的 CustomList,假设 T 是 A1 类和 A2 类,它们都扩展了 A 类,这是一个自定义类。
我需要这样做:
public class CustomList<T> extends ArrayList<T>
{
public CustomList()
{
super();
}
public boolean add(T obj)
{
/*The method getCustomBoolean() is not defined for the type T*/
if(obj.getCustomBoolean())
{
super.add(obj);
}
return true;
}
}
getCustomBoolean()
方法是一个A 类
方法,并且仅对A1
和A2
使用此CustomList >,我确定 obj.getCustomBoolean()
不会导致异常。
我需要一种方法来指定 T 是 A 的子类。
最佳答案
将类(class)的第一行更改为此。
public class CustomList<T extends A> extends ArrayList<T>
指定 T
可以是 A
的子类型的任何类型。它将允许您在类代码中的 T
对象上使用类型为 A
的方法。
关于java - 使用 T 类扩展 ArrayList<T> 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23239393/