Reputation: 2172
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
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
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
Reputation: 46943
Doing this in an array will not be efficient, especially if you need to provide the array's shrinking:
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
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