首先不建议你这么写,继承不是这么用的
其次的话,如果你非要这么写不可,反正list里面的东西都是跟第0个一样,直接复制i份不就完了?
List<Shape> shapes = Collections.nCopies(i, list.get(0));
list.addAll(shapes);
大体就这么写吧
【 在 tortelee (hust-wh) 的大作中提到: 】
: 标 题: ArrayList<Shape> 里add new object
: 发信站: 水木社区 (Mon Jul 12 21:36:18 2021), 站内
:
: 问题描述:
: 有一个Shape, rectangle, circle 继承此类;
: 有一个List, List<Shape>.
: 现在我想写一个方法,
: addMoreToList(ArrayList<Shape> list, int i){
:
: }
: 往list里面添加i个新对象。比如本身是list<circle>, i = 1, 那么再加入一个circle对象。
:
: 我是这么想的: 如果用反射,在方法里获得具体的shape类是可以实现的,
: Class c = list.get(0).getClass();
: 但是接下来生成对象怎么写?
: Shape s = (Shape) c.newInstance()
: 这样写的话,生成的还是shape,并不是具体的circle或者 rectangle.
:
: 求指教
: --
:
: ※ 来源:·水木社区
http://www.mysmth.net·[FROM: 223.166.166.*]
--
FROM 103.107.216.230