我一直在尝试创建一个程序,通过对象获取数组输入并传递参数(模拟ArrayList)。
我一直得到 java.lang.ArrayIndexOutOfBoundsException ,其中我猜我没有正确访问数组..
如何增强测试对象和/或构造函数?
public class MyArrayList{
public int[] x;
public MyArrayList( ){
x = new int[0];
}
public MyArrayList(int[] k)
{
for (int i = 0; i < x.length; i++)
x[i] = k[i];
k = x;
}
public void add(int index).......
public int size().....
public int get(int index).....
public void set(int index, int value).......
public String toString( )........
以下是我遇到麻烦的课程。
public class TestMyArrayList
{
public static void main(String[] args)
{
MyArrayList test = new MyArrayList();
test.x[0] = 1;
test.x[1] = 2;
test.x[2] = 3;
test.x[3] = 4;
test.x[4] = 5;
test.add(2);
test.set(1,3);
int a, b;
String c;
a = test.size( );
b = test.get(5);
c = test.toString( );
System.out.println("The size of the array is" + a);
System.out.println("The value at that position is " + b);
System.out.println("The resulting string is: " + c);
}
}
答案 0 :(得分:1)
构造函数中的这一行是数组x
初始化的唯一位置(在您显示的代码中):
x = new int[0];
它创建一个零长度数组。假设您没有在其他地方重新初始化阵列,那么所有这些线肯定会失败:
test.x[0] = 1;
test.x[1] = 2;
test.x[2] = 3;
test.x[3] = 4;
test.x[4] = 5;
因为您的数组长度为零。所以:
你的其他构造函数:
public MyArrayList(int[] k) {
for (int i = 0; i < x.length; i++)
x[i] = k[i];
k = x;
}
也有一些问题:
x
重新初始化为与提供的数组相同的大小。k = x
基本上是无操作,因为它实际上并没有改变k
指向方法之外的内容。总的来说,它看起来应该更像这样:
public MyArrayList(int[] k) {
super();
if(k != null) {
x = new int[k.length];
for (int i = 0; i < x.length; i++) {
x[i] = k[i];
}
} else {
x = null;
}
}