我再次寻求技术支持。
我需要在一个类中定义一个自定义类型,我已经做到了:
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,所以我仍然习惯它,我是否缺少明显的东西?。
答案 0 :(得分:2)
您只能创建一个不包含任何对象的数组,因此this.CustomType [0]为空。
您应该将对象添加到数组:
public MainClass() {
myArray = new CustomType[1024]
for (int i =0; i<myArray.length;i++ {
myArray[i] = new CustomType();
}
System.out.println(this.myArray[0].varB);
}
还应该将CustomType
的成员设为私有,并通过getter和setter访问它。
答案 1 :(得分:1)
两件事,
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
,这是不必要的开销。
答案 2 :(得分:1)
java中的数组是对象。您发布的代码的下一行创建了一个1024个元素的数组,其中每个元素均为null。
myArray = new CustomType[1024];
如果要将实际对象放置在名为myArray
的数组中,则需要创建类CustomType
的实例并将其分配给数组的元素,例如:
CustomType instance = new CustomType();
myArray[0] = instance;
然后您可以执行以下代码行,并且不会抛出NullPointerException
。
System.out.println(myArray[0].varB);
答案 3 :(得分:-1)
以下是获取varB
值的完整代码。您可以避免在其中声明CustomType[] myArray
public class Test
{
private static class CustomType
{
public byte[] varA;
public int varB;
public CustomType() {
varA = new byte[3];
varB = 13;
}
}
public static void main(String... args)
{
System.out.println(new CustomType().varB);
}
}
答案 4 :(得分:-1)
解决方案是向该数组添加一些元素。有关更多信息,请参见以下步骤。
构造函数
,然后您创建了一个大小为1024的CustomType空数组,并尝试访问不存在的第一个元素(默认为null),并尝试对该null引用执行操作。因此,您将收到NullPointerException。