I am creating a game, and it requires an infinite number of Rectangles.
For example, let's say I name the variables car:
public Rectangle car1;
public Rectangle car2;
public Rectangle car3;
and so on,
Would there be an easier way? Like:
public int carNumber;
public Rectange car + carNumber;//if carNumber was one, it would be called car1
Also, I will need to test if the rectangles contain others.
解决方案
You can't and shouldn't try to declare an infinite number of anything -- just doesn't make sense. Instead use a collection such as an ArrayList that can hold a variable number of object references. e.g.,
private List carList = new ArrayList<>();
This won't work:
public Rectange car + carNumber;//if carNumber was one, it would be called car1
because variable names don't work that way, they can't be created by concatenating Strings. But don't worry about this, because the ArrayList will take care of this. The third item in the list would be obtainable easy enough: carList.get(2).
To see if any Rectangles in the list contain another Rectangle use a for loop and iterate through the collection:
for (Rectangle rect : carList) {
if (rect.contains(testRectangle) {
// this item contains the test Rectangle
}
}