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

[3084 byte] By [Joe_ha] at [2007-11-27 5:35:58]
# 1

And I assume your question is why you aren't getting the results you expect?

Looks like an off-by-one error to me. Either you're not copying the first part of the array correctly, or not copying the second part correctly. More testing would show you which. (Hint: Just test one insert, not three. Keep your tests simple.)

DrClapa at 2007-7-12 15:05:51 > top of Java-index,Java Essentials,New To Java...
# 2

Ugh. Guess I didn't try the one thing that was wrong with it.

I thought that System.arraycopy() copied everything up to the limit inclusive, apparently it doesn't.

The correct algorithm is (in the unlikely event anyone wants to know)

int[] newVector = new int[vector.length + 1];

System.arraycopy(vector, index, newVector, index + 1, vector.length - index);

if(index > 0)

System.arraycopy(vector, 0, newVector, 0, index);

newVector[index] = number;

vector = newVector;

size++;

Anyway, thanks for the response.

Joe

Joe_ha at 2007-7-12 15:05:51 > top of Java-index,Java Essentials,New To Java...