-
Arraylist query
Hi,
I have an assignment to create an object and add it to an ArrayList of existing objects. The objects from the Arraylist are drawn on a JPanel.
I need to check the dimensions of the existing objects against the dimensions of the newly created object prior to it being added to the ArrayList.
I'm unsure how to go about this.
a brief snippet of my code is:
Code:
cars = new ArrayList();
Car c = new Car(x, y, dx, dy);
for (int i = 0; i < cars.size(); i++){
Car car = (Car)cars.get(i);
// It's here where I am confused. I need to interrogate the x,y values of existing Cars checking that the co-ordinates are not already in use. If so I'll regenerate the co-ordinates and perform the loop again until the new co-ordinates do not clash with any existing object in the ArrayList.
cars.add(c);
Can someone please point me in the right direction?
Thanks
-
this is what i've in mind:
you want to check the bounds of car (in the arraylist), if they clash, then try incrementing the x,y,dx,dy values until you find one that is outside of the bounds....
that code snippet is not enough to give detailed advice...
-
That is exactly what I'm trying to solve. I can't post more code as this is for an assessment. What I'm struggling to achieve is obtaining the individual x,y,dx,dy values of each of the cars in the arraylist to check that they don't clash with the newly created car.
Is it simply a case of including this in the for loop block to crosscheck the new object with each existing object in the ArrayList:
if (car.getBounds(x, y, dx, dy) == (c.getBounds(x,y,dx,dy)
-
i would write a small prog to test the code.
for example:
Code:
public void add(Car c){
for (int i = 0; i < cars.size(); i++){
Car d = cars.get(i);
Point p = c.getLocation();
if(c.intersects(d)){
p.x += (int)d.getWidth() + 1;
c.setLocation(p);
}
}
cars.add(c);
}
*Car extends Rectangle
-
Thanks angryboy - you've given me some food for thought there. Appreciated.