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.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Bill
  • 3
  • 2
  • I think you're looking for `i - 1`. – shmosel Apr 16 '18 at 23:44
  • 1
    What exactly do you want to do? You have some array called `values`, with size - lets say 5 - and you want what? To have it shrink to 4 elements? Or do you want to replace one value in your array? – Neuron Apr 16 '18 at 23:46
  • Remove the element and shrink the array by one. – Bill Apr 16 '18 at 23:55
  • Possible duplicate of [Removing an element from an Array (Java)](https://stackoverflow.com/questions/642897/removing-an-element-from-an-array-java) – Neuron Apr 17 '18 at 00:44

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.

Neuron
  • 5,141
  • 5
  • 38
  • 59