Home > database >  How to create multiple variables in java indexed by numbers?
How to create multiple variables in java indexed by numbers?

Time:06-18

I'm making some code, and just realized that I need to create many variables. For instance, I want to create multiple variables that all of them are similar, except just in the index.

Instead of doing 50 times

student1  = new student(param1, param2, param3, etc)
...
student50  = new student(param1, param2, param3, etc)

I was thinking of something like

For (int i=1; i<50; i   ){
  student i   = new student(param1, param2, param3, etc)
}

Is it possible?

CodePudding user response:

Use an array or a List. (Note: in Java, it is best for class names to be capitalized.)

student[] students = new student[50];
for(int i = 0; i < 50; i  ){
  students[i] = new student(/* ... */);
}
// access like students[0] for first student
  •  Tags:  
  • java
  • Related