gpt4 book ai didi

初始化数组对象时出现java.lang.ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-02 05:26:56 25 4
gpt4 key购买 nike

我有一个自定义类,并以经典方式从中创建一个数组。但是当我尝试访问并初始化其各个元素时,我得到了 ArrayIndexOutOfBoundsException。简而言之,以下简单的几行代码在 android 中给我带来了麻烦:

Coordinate[] test;
test = new Coordinate[]{}; // I still get the error without having this line
test[0]= new Coordinate(4,5);

我需要在 for 循环中以动态方式初始化数组中的对象。所以 test = new Coordinate[]{cord1,cord2}; ,虽然它有效,但不能解决我的问题。

附注我知道如何使用 ArrayList 对象,并且在代码的其他部分中使用它。但我有点被迫以经典的方式创建坐标。

提前致谢。

最佳答案

您应该创建一个非空数组:

test = new Coordinate[size];

其中大小 > 0。

否则,您的数组为空,并且 test[0] 会导致出现异常。

这也应该有效(假设您只想要数组中的一个元素):

Coordinate[] test = new Coordinate[]{new Coordinate(4,5)};

关于初始化数组对象时出现java.lang.ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25928123/

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