How do I remove objects from an array in Java?

  Uncategorized

To remove objects from an array in Java you have to make a List out of the array with Arrays.asList(), and call remove(object) on all the appropriate elements. Then call toArray() on the ‘List’ to make back into an array again. This is not terribly performant, but if you use it in a properly way, you can do it like this.

List list = new ArrayList(Arrays.asList(array));
list.remove(objectToRemove);
array = list.toArray(array);

This does work with not only with String arrays. You can arrays of every Class to remove objects from your array. Here is another simple Example for a List of Cars.

List list = new ArrayList(Arrays.asList(array));
list.remove(objectToRemove);
array = list.toArray(array);

Thats all. You only have to change the instantiation of the ArrayList to match with your array. So you can delete objects from arrays of any Class.