Removing Objects from an Array in Java
When working with arrays in Java, you may encounter situations where you need to remove specific objects or values. In particular, you may wonder how to delete elements equal to a given value. This question examines how to remove all occurrences of "a" from an array of strings.
To address this, one solution is to Utilize the ArrayList and List.removeAll method. By converting the array to a list, you can leverage the removeAll method to filter out and remove all instances of "a". Subsequently, you can convert the updated list back to an array.
List<String> list = new ArrayList<>(Arrays.asList(foo)); list.removeAll(Arrays.asList("a")); foo = list.toArray(foo);
This approach retains the array's size, but empty elements may be added to the end. To obtain a new array with the appropriate size, an alternative method can be employed:
foo = list.toArray(new String[0]);
The above is the detailed content of How to Efficiently Remove Objects from a Java Array?. For more information, please follow other related articles on the PHP Chinese website!