I would suggest you use LinkedList instead of an array if you want to delete its elements quite often.
It is also easy to implement it with an array (array-> linked list-> remove elements-> array), but it is not very efficient:
I think the most efficient way (if you still want to work with arrays) is to create a new array with only the necessary elements from the old array:
Object[] filteredObjects = new Object[myObjects.length - elemToRemove.length]; int j = 0; for (int i = 0; i < myObjects.length; i++) { if (!shouldRemove(i)) { filteredObjects[j++] = myObjects[i]; } } myObjects = filteredObjects;
I did not show shouldRemove . I think you should create a set of indexes instead of the elemToRemove array (indexes are unique, so this is the preferred option anyway). Then shouldRemove can be changed to elemToRemove.contains(i) .
May offer you another way with Google Collections (I'm not sure if it is effective, but it looks elegant to me):
for (int index : elemToRemove) { myObjects[i] = null; } myObjects = Collections2.filter(Arrays.asList(myObjects), new Predicate<Object>() { @Override public boolean apply(Object obj) { return obj!= null; } }).toArray();
Roman source share