1

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!

3
  • 6
    new B[][] doesn't create any B instances, so there's no where to pass the A argument. Commented Feb 12, 2014 at 22:39
  • Ok thanks! So I have to populate the array by going through it and creating objects like in the first example is that correct? Commented Feb 12, 2014 at 22:45
  • Yes, that is correct. Or use an array initialization expression. Commented Feb 12, 2014 at 22:45

1 Answer 1

3

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);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Oh I thought that by declaring the type of array as a class (in this case the class B), an Array of B objects was created?
No, it only creates an array to hold references to B objects. You still have to create the objects themselves manually.
It's deceptive, because if you create an array of primitives, the array objects are indeed "constructed"...but only because primitives are defined to have default values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.