0

I want to remove a single element from an array. This is what I have tried so far:

for (int i = pos + 1; i < currentSize; i++) 
    values[???] = values[i];
currentSize--;

I'm so confused on what goes inside the [???] If anyone can help I would really really appreciate it.

Bill
  • 3
  • 2

2 Answers2

0

The ??? In this case indicates the index of the array where you wish to get the value from. If you have an array A with elements 5, 10, 15, and 20 then each of the elements can be retrieved with their index. I.e. the index for 5 is 0, for 10 its 1.

An array of size n will have n-1 elements in it due to zero indexing (A[0] is the first element).

0

Arrays are not very kind in nature, as they can't be resized. As soon as you have learned about objects and generics you will pretty much stop using arrays and transition to Collections. But for now, you'll have to create a new (smaller) array and copy all - but one - value. I will keep it very basic, so you learn the most:

int indexToRemove = 3;

Object[] newArray = new Object[values.length - 1];

for (int i = 0; i < newArray.length; i++) {
    if (i < indexToRemove) {
        newArray[i] = values[i];
    } else {
        newArray[i] = values[i + 1];
    }
}

I didn't know of which type your values are, so I just took Object. You may want to replace that.