[英]Filling a generic List with objects of a subclass of an abstract class
假設我們確實有一個名為Figure
的抽象類,並且內部有一個靜態方法addFigure
。 addFigure
應該使用用戶指定類型的對象填充現有列表。
public abstract class AbstractFigure {
public static <T extends AbstractFigure> void addFigure(List<T> list, Class<T> clazz, int n)
{
for (int i = 0; i < n; i++) {
try {
T obj = clazz.newInstance();
list.add(obj);
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
}
}
然后我們有一個子類Square
。
public class Square extends AbstractFigure {
}
調用如下:
public class GenericsProblem{
public static void main(String[] args) {
ArrayList<Square> arrayListSquare = new ArrayList<>();
AbstractFigure.addFigure(arrayListSquare, Square.class, 12);
}
}
如我所假設的那樣,代碼可以正常工作,並且列表中填充了Squares
。
現在,我想重新制作AbstractFigure
以便代替處理現有列表,而是創建並返回一個列表,如下所示:
public abstract class AbstractFigure {
public static <T extends AbstractFigure> List<T> addFigure(Class<T> clazz, int n)
{
List<T> genList = new ArrayList<>();
for (int i = 0; i < n; i++) {
try {
T obj = clazz.newInstance();
genList.add(obj);
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
return genList;
}
}
這是否有可能,如果可以,我該如何調用它?
對的,這是可能的。 您只需要將返回值分配給變量。
List<Square> arrayListSquare = addFigure(Square.class, 12);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.