为什么我们在 java 中有空数组声明

Why do we have null array declaration in java

int[] numbers;

我不能在没有初始化的情况下像上面那样声明后使用数字数组。 完成了使用它的所有步骤。尝试赋值,使用 fill 并尝试 length 并得出结论,这是声明数组的错误方式,但我不明白为什么 Java 有这样的语法。令人困惑。

为什么?因为有时候需要根据条件运行时信息来初始化数组:

void syntheticExample(int[] these, int[] those, int[] theOthers) {
    int[] numbers;

    // ...some work...

    if (/*...some condition...*/) {
        numbers = these;
    } else {
        // ...more work, then:
        if (/*...some other condition...*/) {
            numbers = those;
        } else if (/*...some further condition...*/) {
            numbers = theOthers;
        } else {
            // We'll use our own numbers
            numbers = new int[] {1, 2, 3};
        }
    }

    // ...use `numbers`...
}

这与我们可以在不初始化的情况下声明任何其他类型的变量的原因相同。声明和initialization/assignment是不同的东西,有时它们需要在不同的时间发生。


在这里很有用也很重要:上面的numbers是一个变量,里面包含了一个对象引用。它 指的是 是一个数组(或者什么都不是,如果我们将 null 分配给它)。

您只是定义了对数组的引用,但该引用在您声明之前不会引用任何内容。为此,你需要构造一个数组,唯一的方法就是使用new和link这个新分配的对象作为引用。它在 Java 中非常一致,因为您了解对象是什么以及它们是如何构建的。

int []ref_array;         // this is NOT an array, but a reference to an array, actually refers nothing
ref_array = new int[10]; // new construct a object that contains 10 ints and array refers to it.
ref_array[3];            // means get the object that ref_array refers, get the array inside and take the 4th value stored in it. A handy shortcut...