Home >Java >javaTutorial >How to Efficiently Remove Objects from a Java Array?

How to Efficiently Remove Objects from a Java Array?

DDD
DDDOriginal
2024-12-17 14:05:12393browse

How to Efficiently Remove Objects from a Java Array?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn