Java - 嵌套在 class 中的自定义类型

Java - Custom type nested in class

再次请求技术支持

我需要在 class 中定义一个自定义类型,我是这样做的:

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

当我 运行 它在 System.out.println(this.CustomType[0].varB);

处抛出一个 NullPointerException

我已经测试了 myArray 是否使用 1024 个元素正确初始化并且确实如此,但是我似乎无法访问它们。

我刚从 C++ 转到 Java 所以我还在适应它,我是不是漏掉了什么明显的东西?

你只创建了一个没有任何对象的数组,所以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 访问它。

两件事,

  • 您必须实例化 CustomType。
  • CustomType 不需要访问 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 实例中,这是不必要的开销。

java 中的数组是对象。您发布的以下代码行创建了一个包含 1024 个元素的数组,其中每个元素都为空。

myArray = new CustomType[1024];

如果要将实际对象放入名为 myArray 的数组中,则需要创建 class CustomType 的实例并将它们分配给数组的元素,例如:

CustomType instance = new CustomType();
myArray[0] = instance;

那你可以执行下面这行代码就不会抛出NullPointerException.

System.out.println(myArray[0].varB);

这是获取 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);
    }
}

解决方案是向该数组添加一些元素。有关详细信息,请参阅以下步骤。

  1. 构造函数将被调用,当你创建那个class

  2. 的对象时
  3. 然后您创建了一个空的 CustomType 数组,大小为 1024 并尝试访问第一个不存在的元素(默认为空)并尝试对该空引用执行操作。所以你得到了 NullPointerException。