I’ve something like this
Object[] myObjects = ...(initialized in some way)...
int[] elemToRemove = new int[]{3,4,6,8,...}
What’s the most efficient way of removing the elements of index position 3,4,6,8… from myObjects ?
I’d like to implement an efficient Utility method with a signature like
public Object[] removeElements(Object[] object, int[] elementsToRemove) {...}
The Object[] that is returned should be a new Object of size myObjects.length – elemToRemove.length
You will need to create a new array, since arrays do not change in size (you cannot “remove” elements while keeping the same array, it would create holes somewhere). I suggest this:
This assumes that
elemToRemoveis already sorted, with no duplicates, and contains only indices valid within the source array. TheArrays.copyOf()call is used only to make sure that the runtime type of the new array is identical to that of the source array.If you often have to “remove” data from arrays, thus requiring the creation of new arrays, then Java arrays might not be the most efficient data structure for you.
LinkedListorArrayListmay be more appropriate.