I have a method, seemingly fine, for putting double values into a double array. It is
insert(int i, double value)
where i is the index (array[i]) and value is what I want in that index.
I split the method into edge cases, built in a sufficient safe block of initialized array space (length) and buffered that with a part of the method that doubles the length every time the number of elements is equal or greater than the length. I then put methods for when the input i is greater than the number of items (numItems) of the array and when it is less than numItems. i < numItems is working fine, but when I try to put in
insert(63,3)
insert(15,3)
insert(23,3)
into my (1,-1,5,23) array I only get 2 three’s on the last part of my array. My initial array length is 10, so it’s not a memory issue. I thought it might be a print method error and tried to obtain the last element manually, which told me the index was empty. Thus it is a logic error in my method, which follows.
// 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;
}
The thing is, it’s such simple code that I can’t tell what’s wrong with it. Very intuitive, and very puzzling. Ideas?
below is the whole of the insert method
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;
}
}
In case of any modifications that alter array size (insert or delete) it is recommended to use
java.util.Listimplementations.ArrayList, for example. It saves you from headache with temporary arrays and moving of elements.Also, to copy some elements from array to array you should consider using existing methods like
System.arraycopyand various copying methods fromjava.util.Arrays.