I'll try to keep this as much language agnostic as I can but I'll give the examples in C# since I now know how to solve it that language.
The question came to mind when I was thinking of how could I instantiate many objects of the same type.
Lets say I wanted to create one rectangle, I would do:
Rectangle rect1 = new Rectangle()
Now, if I wanted to create 2 I would do.
Rectangle rect1 = new Rectangle()
Rectangle rect2 = new Rectangle()
This of course is not efficient when you need to create many rectangles.
The problem is, I couldn't use loops just like that to create a many rectangles:
for (int i = 0; i < 100; i++){
Rectangle rect1 = new Rectangle()
}
This obviously doesn't achieve what I am after since I would just create 100 rect1
's.
I was pointed out that you could do something like this: Thanks mootinator
var rectangles = new Rectangle[100];
for (int i = 0; i < 100; i++){
rectangles[i] = new Rectangle();
}
For what I understood, the code creates a data structure (Array? ArrayList?) of they type Rectangle
inside you actually "store" Rectangles.
The hardest thing for me was putting a question for this.
So the questions are:
- What is this called?
- Is this standard / "common" in most OOP based languages? The question actually came up in ActionsScript 3, but is is useful /necessary in any language it might seem.
- Is this the best way for doing this considering that I would the like to, for example, loop this Array and apply a method
.Move()
. - Are there? and what are the other options to do this.