Natecat
Natecat

Reputation: 2172

How to move array elements down from a certain piont?

I have a array of variables, and I want to delete 1 of the elements and then shift the whole array down to fill that spot that was removed. Any help would be greatly appreciated, and before you ask, no this is not homework.

Upvotes: 0

Views: 350

Answers (4)

Robin
Robin

Reputation: 36611

A possible solution is to use the Arrays.asList and List#toArray methods to convert the array temporarily to a List, use the available remove method of the List, and convert it back to an array.

Object[] arrayToShrink = ...;
List<Object> shrinkedList = new ArrayList<Object>( Arrays.asList( arrayToShrink ) );
shrinkedList.remove( objectToRemove );
Object[] shrinkedArray = shrinkedList.toArray( new Object[shrinkedList.size()] );

Short code wise, but most likely not the most efficient solution.

Upvotes: 0

Neifen
Neifen

Reputation: 2595

I Think the best solution would be to use an ArrayList

        ArrayList<String> list = new ArrayList<String>();

        //add Elements
        list.add("test1");
        list.add("test2");
        list.add("test3");

        //remove Element 2 (->1)
        list.remove(1);

        //print Element 2
        System.out.println(list.get(1));
        //output: test3

If you realy want to us an Array:

    private void removeElement(String[] array, int index) {
    final int arrayLength = array.length;
    for (int i = index + 1; i < arrayLength; i++) {
        if (i > 0) {
            array[i - 1] = array[i];

            if (i == arrayLength - 1) {
                array[i] = "";
            }
        }
    }
}

Upvotes: 0

Boris Strandjev
Boris Strandjev

Reputation: 46943

Doing this in an array will not be efficient, especially if you need to provide the array's shrinking:

  • if you do not need to shrink you can just swap all the elements till the end.
  • if you need to shrink, then the only option will be to allocate new array and copy over all the elements.

A better option for this task will be LinkedList. It provides an operation for removing arbitrary element and it does not require any shifting for fixing the collection.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500495

Ideally, use an ArrayList (or some other list implementation) instead, where this is already implemented for you. (The exact implementation you'd want to use will depend on how often you need to perform removals vs how often you need to retrieve or set by index, etc. With more context we could help you more.)

Otherwise, use System.arraycopy.

System.arraycopy(array, index + 1, array, index, array.length - index - 1);
// Assuming it's a reference type array: null out the last element so it
// doesn't prevent garbage collection
array[array.length - 1] = null;

Upvotes: 2

Related Questions