Home > database >  Java - Initialize multiple objects using loop
Java - Initialize multiple objects using loop

Time:10-28

So I have 5 objects that I want to instantiate them using a for-loop

SomeObject obj1, obj2, obj3, obj4, obj5;

//Instead of having to write this
obj1 = new SomeObject();
obj2 = new SomeObject();
obj3 = new SomeObject();

//I want to be able to do this
for (int i = 0; i < 5; i  ) {
    //instantiate the objects with "new" keyword here
}

I have tried using an array, but they only create instances of objects inside the array only, and the original obj1,... didn't change at all

What I tried:

SomeObject obj1, obj2, obj3, obj4, obj5;

SomeObject[] objectArray = {obj1, obj2, obj3, obj4, obj5} //IntelliJ gives warning "Value obj1,... is always null"

for (int i = 0; i < 5; i  ) {
    objectArray[i] = new SomeObject(someRandomValueInsideHere);
}

System.out.println(obj1); //obj1 is still null, even though the loop instantiated the objects
System.out.println(objectArray[0]); //this exists. The whole array is also correctly populated

I read somewhere else about java objects being "passing reference by value". Can someone further explain that? Am I missing something really obvious here?

CodePudding user response:

In Java, declaration and initialization of an object should be as close together as possible, and for newer Java versions you could skip the type on the declaration and replace it with the var keyword.

Maybe this rewrite of your first example explains it better:

var obj1 = new SomeObject();
var obj2 = new SomeObject();
var obj3 = new SomeObject();

But don't think it is equal to JavaScript - in Java you cannot change the type of obj1, obj2 and obj3 later (e.g. with another assignment), the compiler derives it from the initialization.

If you want to have individual names for your variables, this one-by-one is the only way you can initialize them, but don't initialize everything "at the beginning" but as close to the actual usage as possible. (It's called minimize visibility)

If you want to work with an array, as in your second example, and the objects don't need individual names, but index numbers are fine, you would do it like this:

SomeObject[] objectArray = new SomeObject[3];
for (int i = 0; i < 3; i  ) {
    objectArray[i] = new SomeObject(Math.random());
}

System.out.println(objectArray[2]);

var obj1 = objectArray[0];
System.out.println(obj1);

You always have to access the elements of the array with the index ([0] etc.)

But you could assign an element of your array to an individually named variable after the initialization.

  • Related