ArrayList<Brick> tiles = new ArrayList<Brick>();
public void init(){
for(int i=0; i<10; i++) {
tiles.add( new Brick(30,10,Color.red));
}
myPrint(tiles);
}
private static void myPrint(ArrayList<Brick>tiles) {
for (int i = 0; i < tiles.size(); i++)
System.out.println(tiles.toString());
}
上面是我试图将Brick对象添加到arraylist,但无法打印它。
这是Brick类:
public class Brick extends GCompound {
public Brick(int width, int height, Color color) {
GRect rect = new GRect(width, height);
rect.setFilled(true);
rect.setFillColor(color);
}
运行代码时没有显示任何内容。我尝试添加一个toString方法,但它也没有用。
我也试过制作一个ArrayList<GRect> tiles = new ArrayList<GRect>();
,但也无法打印出来。
我的问题是,如何打印矩形对象的arrayList?
修改
如果我不清楚我的目标,这里有一个类似于我想要实现的东西的截图:
我使用for循环制作了这个,但是我将添加必须删除矩形的条件,所以我认为ArrayList最适合。
答案 0 :(得分:1)
在您的Brick
构造函数中,您正在创建GRect
对象,而不是对其进行任何引用。
因此,您需要将GRect
引用的引用保留为Brick
的实例变量,并覆盖toString()
,如下所示:
public class Brick extends GCompound {
private GRect rect;
public Brick(int width, int height, Color color) {
this.rect = new GRect(width, height);
this.rect.setFilled(true);
this.rect.setFillColor(color);
}
@Override
public String toString() {
return "Brick{" +
"Height=" + rect.getHeight() +
"Width=" + rect.getWidth() +
"Color=" + rect.getFillColor() +
'}';
}
}
另外,您在myPrint()
循环内调用tiles.toString()
的{{1}}方法是不必要的,因此请更新for
方法,如下所示:
myPrint