我已称为NumList一个ADT,并已在一类NumArrayList插入元件插入到数组索引越界的java
的实现的方法实现它的,有一个插入件(INT I,双值),其中值插入到数组[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行一个ArrayIndexOutOfBoundsException,或在
tempItems[items.length] = value;
我相信这是想告诉我,我的项目的初始化是错误的,
private double[] items;
private int numItems;
public NumArrayList()
{
items = new double[0];
numItems = 0;
}
但是初始化已经被一个比我更好的程序员批准了,这些错误导致我无处可去。也许是对我应该研究的程序的哪一部分有所了解?
这是真的,但在发布的代码中,tempItems.length等于items.length * 2,因此tempItems [items.length]并不是真正的问题。除非当然,如构造函数所示,这两个都是零。 – Thorn