Click here to Skip to main content
15,939,853 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When testng the remove method, my result tells me that I have an extra element in the initial array. Here's what I have:

public int remove(int index)
for (int i = index; i < numElements - 1; i++)
System.out.println("removing " + i);
arr[i] = arr[i + 1];
return arr[index];

What I have tried:

I've tried differen't things like setting "i" less than numElements plus 1 rather than minus, but I don't think that is where my probelm is occuring. I'm a bit rusty when it comes to Java, but I'm doing my best!
Updated 21-May-19 8:19am

You aren't "removing" anything: you are copying elements into earlier locations, but that doesn't reduce the number of elements in the array.
For example, if arr has 5 elements:
Index:  0  1  2  3  4
Value:  7  8  9  0  1
Then is you call remove with index 2 then after the method arr will be changed:
Index:  0  1  2  3  4
Value:  7  8  0  1  1
This is probably where your "extra element" is coming from.
Share this answer
Consider the situation where there are three elements in your array, and index is 1. So i goes from 1 to 1 (i.e. less than 2 (3-1)). So
for (i = 1; i < 2; i++)
    arr[1] = arr[2];
// but all the remaining elements (including arr[2]) still exist

Your code does not actually remove anything, it just moves all the elements after the one pointed to by index. And the last one in the loop is duplicated.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900