Question

I know I can instantiate an object of another class, with an argument in its constructor like below:

public class A{

    B myB;
    myB = new B(this);

}

public class B{

    A instanceThatCreatedMe;

    B(A myA){
        instanceThatCreatedMe = myA;
    }
}

I want to do the same thing, but when B is created in a 2D array. In other words, to create a 2D array of B objects, with (this) as parameter in their constructor Something like this:

public class A{

    B[][] myBArr;
    myBArr = new B[][](this); //<--- That isn't allowed! Neither is myBArr = new B(this)[][]
}

public class B{
    //No change
    A instanceThatCreatedMe;

    B(A myA){
        instanceThatCreatedMe = myA;
    }
}

Is there a way to do it without having to go through the whole array and setting the instanceThatCreatedMe in each object?

Thank you everyone!

Was it helpful?

Solution

Sorry, but Java doesn't do that for you. Array creation only creates the arrays themselves, but cannot fill them with anything but null. You have to loop through the created arrays manually and create instances to fill them.

Furthermore, however, your example code wouldn't compile to begin with, since you don't specify the size of the array.

What you want, then, is probably something akin to this:

int d1 = 5, d2 = 6; /* Or however large you want the arrays to be. */
myBArr = new B[d1][d2];
for(int i1 = 0; i1 < d1; i1++) {
    for(int i2 = 0; i2 < d2; i2++) {
        myBArr[i1][i2] = new B(this);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top