我制作了一个名为 NumList 的 ADT,并在 NumArrayList 类中实现了它
在实现的方法中,有一个 insert(int i, double value),其中将值插入到 array[i] 中。
int numItems 是一个跟踪数组元素的计数器。
public void insert(int i, double value)
{
if (numItems >= items.length)
{
double[] tempItems = new double [items.length * 2];
for(int j =0 ; j < items.length; j++ )
{
tempItems[j] = items[j];
}
tempItems[items.length] = value;
items = tempItems;
}
else
{
if (i > numItems)
{
items[numItems] = value;
}
else
{
for (int k = i; k < numItems; k++)
{
items[k+1] = items[k];
}
items[i] = value;
}
}
numItems++;
}
这是我的方法,看起来很简单。
public static void main (String[] args)
{
NumArrayList test;
test = new NumArrayList();
//System.out.println("this is how many initial items the initialized array has.");
//System.out.println(test.items);
test.insert(1, 0.1);
System.out.println("have tried to insert value 0.1 @ position 1, that is the second element in array.");
test.print();
是我的测试代码区域,内置于同一个类中。
我收到一个错误,编译器声称我在第 47 行或
处有一个 ArrayIndexOutOfBoundsExceptiontempItems[items.length] = value;
我相信它试图告诉我我的项目初始化是错误的,
private double[] items;
private int numItems;
public NumArrayList()
{
items = new double[0];
numItems = 0;
}
但是初始化已经被比我更好的程序员批准了,这些错误对我来说毫无意义。也许是关于我应该研究该计划的哪一部分的提示?
最佳答案
你的初始化肯定是错误的。合理的默认大小是多少?对于ArrayList,答案是10。您可以将其设置为任何您喜欢的值,但不能是零!如果将大小为 0 的数组的长度加倍,新数组的长度仍为 0。
int capacity; //stores the size of the array (items available)
int numItems; //stores how many items are actually stored in the array.
public NumArrayList() {
items = new double[10];
numItems = 0;
capacity = 10;
}
关于java - 将元素插入数组索引越界java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12630892/