我再次请求技术支持。
我需要定义一个类中的自定义类型,我已经做了这样的:
public class MainClass {
private class CustomType {
public byte[] varA;
public int varB;
public CustomType() {
varA = new byte[3];
varB = 13;
}
}
private CustomType[] myArray;
public MainClass() {
myArray = new CustomType[1024]
System.out.println(this.CustomType[0].varB);
}
}
当我运行它抛出一个NullPointerException
在System.out.println(this.CustomType[0].varB);
我测试过,如果myarray的才能正确使用1024个元素初始化它,但是我似乎无法访问它们。
我刚刚从C ++到Java移动,所以我还是习惯了,我失去的东西明目张胆?
两件事情,
MainClass.this
,所以你可以把它静态的。所以
public class MainClass {
private static class CustomType {
public byte[] varA;
public int varB;
public CustomType() {
varA = new byte[3];
varB = 13;
}
}
private CustomType[] myArray;
public MainClass() {
myArray = new CustomType[1024];
for (int i = 0; i < myArray.length; ++i) {
this.CustomType[i] = new CustomType();
}
// Or
Arrays.setAll(myArray, CustomType::new);
System.out.println(this.CustomType[0].varB);
}
}
不使其静态存储MainClass.this
在每一个CustomType
实例,它是不必要的开销。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句