Vector.insert() method
Hey folks,
I'm trying to implement a Vector-ish datatype (I know Java has a great one already, but I'm trying my hand at implementing new stuff).
Anyway, all it's supposed to do is take in an index and a number, create a new array 1 integer longer than the previous, copy all the data around the insertion index into the new array, and then insert the number at the index.
Here's the code:
Any help would be appreciated.
Thanks!
Joe
privatevoid insertAssistant(int number,int index)
{
//Create a new array large enough to hold an insertion
int[] newVector =newint[vector.length + 1];
//Copy all values at indices greate than parameter index to the new array
System.arraycopy(vector, index, newVector, index + 1, vector.length - index - 1);
//Don't try to copy to a negative index
if(index > 0)
System.arraycopy(vector, 0, newVector, 0, index - 1);
//Insert the desired number
newVector[index] = number;
//Set the class-visible array to the array with the new number
vector = newVector;
//Increment the number of user-defined values in the vector
size++;
}
And, here's my JUnit test:
publicvoid testInsert()
{
Vector vector =new Vector();
for(int i = 0; i < 10; i++)
{
vector.add(i);
}
for(int i = 0; i < 10; i++)
{
System.out.println(vector.at(i));
}
vector.insert(200, 0);
vector.insert(34, 10);
vector.insert(100, 5);
System.out.println("BREAK\n\n\n");
for(int i = 0; i < vector.size(); i++)
{
System.out.println(vector.at(i));
}
System.out.println("SIZE: " + vector.size());
}
and the JUnit result:
0
1
2
3
4
5
6
7
8
9
BREAK
200
0
1
2
0
100
4
5
6
7
0
34
0
SIZE: 13

