Question

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. <-- I know how to do this.

Was it helpful?

Solution

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<Rectangle> 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
  }
}

OTHER TIPS

You would use an ArrayList to do this

Arrays are static memory allocation. You always need to state the size of the array upon array creation, thus not possible to have an "infinite" array. What you are looking for is called dynamic memory allocation.

One example of using dynamic memory is ArrayList.

ArrayList allows you to expand it when elements are added and shrink it when elements are removed. You can expand the size of an ArrayList so called "infinitely" by keep on adding elements into it. However the limit for number of elements you can add to it depends on how much memory your system has.

Basically, dynamic memory allocation is what you are looking for. You may also consider using Vector.

Sorry You can't do it in JAVA. You can't create a variable name dynamically.

I am creating a game, and it requires an infinite number of Rectangles.

You will get OutOfMemory in case of infinite number of Rectangles. Please think about it again.


You can use a static array if the number of rectangles is already known.

Rectangle[] rec = new Rectangle[size];  

//get the first Rectangle 
Rectangle first = rec[0];

// get the total no of Rectangles
int length = rec.length();

in general code like:

car1 = "blue";
car2 = "red";
car3 = "green";

is 99% of the time better expressed as an array

cars = ["blue", "red", "green"]

In Java arrays are of fixed length when you initialize them, so you could just make a big one or you could use an ArrayList as an above commenter mentioned which is a list-structure that allows for one by one additions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top