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

This output gives me:

  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

I would like to make 10 elements with values 0f 10 and 20 each.

3
  • 2
    Without the code for Rectangle it is difficult to see what is going wrong. Can you include this too? Commented Mar 17, 2012 at 20:56
  • what should be 10 and 20 ? The top left corner ? Then you have to use the constructor taking four integers. In the version you have posted you're just initializing a rectangle's width and height, leaving the top left corner at 0,0. Commented Mar 17, 2012 at 20:57
  • @sgmorrison - Rectangle is part of Java libraries. Commented Mar 17, 2012 at 20:58

2 Answers 2

5

The constructor that gets two arguments is this:

Rectangle(int width, int height) 

Which doesn't set x and y.

You can either use this constructor:

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

E.g.

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

Or set x and y after creating the object:

for (int i=0; i < 10; i++)
{
    Rectangle rect = new Rectangle();
    rect.setLocation(10, 20);
    list.add(rect);
}
Sign up to request clarification or add additional context in comments.

Comments

2

The Rectangle constructor that you're using takes a width and a height. You're not setting the x and y values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.