Reputation: 13
Okay so I have a shape arraylist containing a rectangle. How would i obtain the x coordinate of that rectangle from the arraylist?
I think i didn't make it clear so here it is: So here is the arraylist:
ArrayList<Shape> shapes = new ArrayList<Shape>() ;
Creating the shape:
Shape rec1 = new Rectangle(100,100,200,200);
shapes.add(rec1);
now how can i get the x coordinate? I tried:
Shape j = (Shape)shapes.get(i);
j.getX()
But that didn't work.. error: cannot find symbol
Upvotes: 0
Views: 1570
Reputation: 37875
Shape does not necessarily have a single x coordinate. So you could change your ArrayList so its type is Rectangle:
ArrayList<Rectangle> shapes = new ArrayList<Rectangle>();
Or you can get the bounds with getBounds:
Shape s = shapes.get(i);
double x = s.getBounds().getX();
For a Rectangle this basically creates a copy of itself but if you have to include other shapes you don't really have a choice (except some kind of case-by-case casting).
Upvotes: 1
Reputation: 4844
Cast the object to a Rectangle
, not a Shape
(getX()
is defined in class Rectangle
, not in Shape
):
Rectangle r = (Rectangle) shapes.get(i);
r.getX();
However this is not probably what you want: if you have a list of Shape
s, not all of them will be Rectangle
s. You can check whether the object is a Rectangle
or not before using it:
Shape j = (Shape) shapes.get(i);
if (j instanceof Rectangle) {
((Rectangle) j).getX();
}
Upvotes: 1