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

How Can I Efficiently Remove Objects from a Java Array?

Susan Sarandon
Susan SarandonOriginal
2024-12-29 12:59:11333browse

How Can I Efficiently Remove Objects from a Java Array?

Removing Objects from an Array in Java

In Java, arrays are fixed-length collections of elements. When you need to remove an object from an array, there is no straightforward built-in method to do so.

Consider an array of strings:

String[] foo = { "a", "cc", "a", "dd" };

Solution: Array to List and Back

One approach to remove objects from an array is to convert it to a list, modify the list, and then convert it back to an array.

List<String> list = new ArrayList<>(Arrays.asList(foo));
list.removeAll(Arrays.asList("a"));
foo = list.toArray(foo);

This process retains the original array's size, with the elements after the last remaining element set to null.

Solution: New Array from List

If you want a new array exactly the size needed, you can do the following:

foo = list.toArray(new String[list.size()]);

Using Reusables

For frequent usage, you might consider creating a pre-defined empty string array constant:

private static final String[] EMPTY_STRING_ARRAY = new String[0];

Then, the removal function can be rewritten as:

List<String> list = new ArrayList<> ();
Collections.addAll(list, foo);
list.removeAll(Arrays.asList("a"));
foo = list.toArray(EMPTY_STRING_ARRAY);

Alternatively, you can use the approach suggested by cynicalman:

foo = list.toArray(new String[list.size()]);

The above is the detailed content of How Can I 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