gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:02:03 25 4
gpt4 key购买 nike

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

public class A{

B myB;
myB = new B(this);

}

public class B{

A instanceThatCreatedMe;

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

我想做同样的事情,但是当 B 是在二维数组中创建时。换句话说,创建 B 对象的二维数组,并在其构造函数中使用 (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);
}
}

关于Java - 创建类的数组时将参数传递给类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21741405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com