使用循环在arrayList中设置值

chi*_*ief 1 java

 ArrayList<Rectangle> list = new ArrayList<Rectangle>();
  for (int i=0; i < 10; i++)
  {
  list.add(new Rectangle(10,20));

  }

 for (int i=0; i < list.size(); i++ )
  {
     Rectangle rec = list.get(i);
     System.out.print("Element " + i +"  ");
     System.out.println("x=" + rec.getX()+"   y=" + rec.getY());
  }
Run Code Online (Sandbox Code Playgroud)

此输出给我:

  Element 0  x=0.0   y=0.0
  Element 1  x=0.0   y=0.0
  Element 2  x=0.0   y=0.0
  Element 3  x=0.0   y=0.0
  Element 4  x=0.0   y=0.0
  Element 5  x=0.0   y=0.0
  Element 6  x=0.0   y=0.0
  Element 7  x=0.0   y=0.0
  Element 8  x=0.0   y=0.0
  Element 9  x=0.0   y=0.0
Run Code Online (Sandbox Code Playgroud)

我想制作10个值分别为0f 10和20的元素。

MBy*_*ByD 5

得到两个参数构造函数是这样的:

Rectangle(int width, int height) 
Run Code Online (Sandbox Code Playgroud)

哪个不设置x和y。

您可以使用以下构造函数:

Rectangle(int x, int y, int width, int height) 
Run Code Online (Sandbox Code Playgroud)

例如

list.add(new Rectangle(10,20,0,0));
Run Code Online (Sandbox Code Playgroud)

或在创建对象后设置x和y:

for (int i=0; i < 10; i++)
{
    Rectangle rect = new Rectangle();
    rect.setLocation(10, 20);
    list.add(rect);
}
Run Code Online (Sandbox Code Playgroud)