0

I want to be able to give the program a number between 2 and 10 and it create that many objects from the same class in Java.

I'm not sure the best way to do this. The only way I can think of is that I make 10 if/else if statements and make the objects that way.

if (num == 2){
  Class object1 = new Class(1)
  Class object2 = new Class(2)

}
else if (num == 3){
  Class object1 = new Class(1)
  Class object2 = new Class(2)
  Class object3 = new Class(3)
}

.
.
.

else if (num == 10){
  Class object1 = new Class(1)
  Class object2 = new Class(2)
  Class object3 = new Class(3)
  Class object4 = new Class(4)
  Class object5 = new Class(5)
  Class object6 = new Class(6)
  Class object7 = new Class(7)
  Class object8 = new Class(8)
  Class object9 = new Class(9)
  Class object10 = new Class(10)
}

Is there a better way to do this? I'm still learning to code so I'm not the best at it. Someone said something about an array of objects but I don't know what that is or if it relates to this problem. Thank you.

2 Answers2

4

Given the input you can create the objects inside a for loop and add it one-by-one in an ArrayList.

List<Class> list = new ArrayList<>();

for(int i = 0; i < n; i++){ // n is the number of objects to be created.
   list.add(new Class(i+1));
}
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
2

Use an array:

Class[] objects;

then

objects = new Class[num];
for (int i = 1; i <= num; ++i) {
    objects[i-1] = new Class(i);
}

Note that array indexing starts at 0.

It's worth through through the arrays tutorial on the Oracle Java website (or, of course, the arrays section of any good beginner's Java book or tutorial).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875