繁体   English   中英

Java-在创建该类的数组时将参数传递给类构造函数

[英]Java - Passing a parameter to a class constructor, when an array of that class is being created

我知道我可以实例化另一个类的对象,并在其构造函数中使用如下所示的参数:

public class A{

    B myB;
    myB = new B(this);

}

public class B{

    A instanceThatCreatedMe;

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

我想做同样的事情,但是当在2D数组中创建B时。 换句话说,要创建一个由B对象组成的2D数组,并以(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;
    }
}

有没有一种方法可以不必遍历整个数组并在每个对象中设置instanceThatCreatedMe?

谢谢大家!

抱歉,Java不能帮您。 数组创建只能自己创建数组,而不能用null填充任何内容。 您必须手动遍历创建的数组并创建实例以填充它们。

此外,由于您未指定数组的大小,因此示例代码不会首先开始编译。

那么,您想要的可能与此类似:

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM