初始化数组对象时发生java.lang.ArrayIndexOutOfBoundsException

初始化数组对象时发生java.lang.ArrayIndexOutOfBoundsException,java,android,arrays,initialization,indexoutofboundsexception,Java,Android,Arrays,Initialization,Indexoutofboundsexception,我有一个自定义类,我用一种经典的方式从中创建了一个数组。但是当我尝试访问和初始化它的单个元素时,我得到了ArrayIndexOutOfBoundsException。简而言之,以下几行简单的代码给我在安卓系统中带来了麻烦: Coordinate[] test; test = new Coordinate[]{}; // I still get the error without having this line test[0]= new Coordinate(4,5); 我需要在for循环中以

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

Coordinate[] test;
test = new Coordinate[]{}; // I still get the error without having this line
test[0]= new Coordinate(4,5);
我需要在for循环中以动态方式初始化数组中的对象。 所以
test=新坐标[]{cord1,cord2},但它不能解决我的问题

另外,我知道如何使用ArrayList对象,我在代码的其他部分也使用了它。 但我有点被迫以一种经典的方式创建坐标


提前感谢。

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

test = new Coordinate[size];
其中
size
>0

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

这也应该起作用(假设数组中只需要一个元素):


您不指定数组的大小

例如,为了创建一个大小为10的数组,您可以编写:

Coordinate[] test;
test = new Coordinate[10]; // Creating array of size 10
test[0]= new Coordinate(4,5);

请记住,“经典”数组的大小是固定的

数组是连续的内存块,因此您应该提及数组大小(非负)


您似乎忘记指定数组大小:

Coordinate[] test;
test = new Coordinate[20]; // <-- array of size 20
test[0]= new Coordinate(4,5);
Coordinate[]测试;

测试=新坐标[20];//
test=新坐标[]{}
test=新坐标[0]相同

您正在创建长度为零的数组,然后尝试访问其第一个成员

您至少需要创建一个长度为1的数组:

test = new Coordinate[0];
我们使用你的计划:

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

谢谢大家的回答。 我想我会用以下方法解决这个问题: 1.动态确定数组的大小
2.用该大小初始化我的数组。

如果这样可以解决问题,我仍然不知道数组的大小。有没有办法动态创建它?@user2770916不幸的是没有。为了获得动态大小数组,您需要使用
ArrayList
。如果确实需要使用“普通”数组,则需要估计数组的最大大小,并将其大小设置为该数字。
test = new Coordinate[0];
test = new Coordinate[]{new Coordinate(4,5)};