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 对象添加到数组列表中,但未能打印它。
这是 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 最适合。
最佳答案
在您的 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() +
'}';
}
}
此外,您在 for
循环内调用 tiles.toString()
的 myPrint()
方法是不必要的,因此更新 myPrint
方法如下所示:
private static void myPrint(ArrayList<Brick> tiles) {
System.out.println(tiles);//remove for loop and printing tiles calls toString()
}
关于java - 如何打印 GRect 的 ArrayList (Java acm),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43710567/