[Q#6681704][A#6681899] How to remove elements from an array in java even if we have to iterate over array or can we do it directly?
https://stackoverflow.com/q/6681704
Possible Duplicates: How do I remove objects from an Array in java? Removing an element from an Array (Java) // can this work , Is there a better way ? to remove certain elements from an array in this case the first one .
Answer
https://stackoverflow.com/a/6681899
Without a for loop : Tip If you can, stick with List, you'll have more flexibility.
APIzation
String[] array = new String[]{"12","23","34"};
java.util.List<String> list = new ArrayList<String>(Arrays.asList(array));
list.remove(0);
String[] new_array = list.toArray(new String[0]);
package com.stackoverflow.api;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Human6681899 {
// not very optimal from a complexity point of view
public static Object[] removeElementFromArray(Object[] array, int index) {
List<Object> list = new ArrayList<>(Arrays.asList(array));
list.remove(index);
return list.toArray();
}
}
package com.stackoverflow.api;
import java.util.ArrayList;
import java.util.Arrays;
/**
* How to remove elements from an array in java even if we have to iterate over array or can we do it directly?
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/6681899">https://stackoverflow.com/a/6681899</a>
*/
public class APIzator6681899 {
public static String[] removeElement(String[] array) throws Exception {
java.util.List<String> list = new ArrayList<String>(Arrays.asList(array));
list.remove(0);
return list.toArray(new String[0]);
}
}