gpt4 book ai didi

java - Java 2D数组大小更改错误

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

我正在尝试使用 Arrays.copyOf 和 import java.util.Arrays 来调整数组的大小,但由于某种原因,即使控制台输出数组长度为 4,就像我尝试时应该的那样为数组第 4 行中的任何内容分配一个值,它在尝试为第 4 行中的某些内容分配值的行上给我一个 nullPointerException。任何人都可以向我解释一下吗?

import java.util.Arrays;
import static java.lang.System.out;

public class Main {
static int TTT[][] = new int[3][3];

public static void main(String[] args) {
TTT = Arrays.copyOf(TTT, 4);
out.print(TTT.length);
TTT[3][0] = 2;
}
}

这给了我一个输出:

4Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:13)

有谁知道为什么会发生这种情况吗?另外,还有一个更好的方法对我来说也可以创建一个可以更改大小的数组吗?如果是这样,请给我一些示例代码!

最佳答案

来自documentation :

Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For any indices that are valid in the copy but not the original, the copy will contain null. Such indices will exist if and only if the specified length is greater than that of the original array. The resulting array is of exactly the same class as the original array.

发生的情况是数组大小增加了,因此在 TTT[3] 位置创建了对 int[3] 的新引用,并用 null 如文档所述。数组具有基本类型这一事实并不意味着它应该自行初始化内部数组。

尝试:

TTT = Arrays.copyOf(TTT, 4);
TTT[3] = new int[3];

关于java - Java 2D数组大小更改错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11404822/

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