gpt4 book ai didi

java - 使用循环在 arrayList 中设置值

转载 作者:行者123 更新时间:2023-11-29 06:42:36 25 4
gpt4 key购买 nike

 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());
}

这个输出给我:

  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

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

最佳答案

constructor that gets two arguments这是:

Rectangle(int width, int height) 

没有设置 x 和 y。

您可以使用此构造函数:

Rectangle(int x, int y, int width, int height) 

例如

list.add(new Rectangle(10,20,0,0));

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

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

关于java - 使用循环在 arrayList 中设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9753628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com