我有一种方法,看起来不错,可以将双精度值放入双精度数组。这是
insert(int i, double value)
其中 i 是索引 (array[i]) 和 value 是我想要的索引。
我将该方法拆分为边缘情况,构建在一个足够安全的初始化数组空间(长度)块中,并使用该方法的一部分进行缓冲,每次元素数量等于或大于长度时,该方法的长度加倍。然后,当输入 i 大于数组的项数 (numItems) 以及小于 numItems 时,我设置了方法。i < numItems 工作正常,但是当我尝试放入时
insert(63,3)
insert(15,3)
insert(23,3)
在我的(1,-1,5,23)
阵列中,我在阵列的最后一部分只得到 2 个三。我的初始数组长度是 10,所以这不是内存问题。我认为这可能是打印方法错误并尝试手动获取最后一个元素,这告诉我索引为空。因此,这是我的方法中的一个逻辑错误,如下所示。
// if i is greater than the number of items, insert value into numItems index,
// and not any farther. e.g. if i = 100000 and numItems = 10, put value into
// items[10] and not items[100000];
if (i > numItems)
{
items[numItems] = value;
numItems++; //add to counter
return;
}
问题是,它是如此简单的代码,我不知道它有什么问题。非常直观,也非常令人费解。想法?
下面是整个插入方法
public void insert(int i, double value) //insert value into array[i]
{
if(i < 0)
{
System.out.println("i < 0; please input i >= 0 for array indices."); //an array cannot have an indice < 0;
return;
}
if (numItems >= items.length) // if the number of items becomes equal or greater than the array containing it
{
double[] tempItems = new double [items.length * 2]; // create a new array double the size of current
for(int j =0 ; j < items.length; j++ ) //and copy all elements into the new array
{
tempItems[j] = items[j];
}
items = tempItems; //set the temp array as the main array.
}
if (i > numItems) //if i is greater than the number of items, insert value into numItems index, and not any farther.
{ // i.e. if i = 100000 and numItems = 10, put value into items[10] and not items[100000];
items[numItems] = value;
numItems++; //add to counter
return;
}
if ( i < numItems) //if i is inside the used boundaries of the array
{
for (int k = numItems; k > i; k--) //shift values over to the right.
{
items[k]=items[k-1];
}
items[i] = value; //and insert value into i
numItems++; //add to counter
return;
}
}