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
Release: 2024-12-29 12:59:11
Original
319 people have browsed it

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" };
Copy after login

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);
Copy after login

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()]);
Copy after login
Copy after login

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];
Copy after login

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);
Copy after login

Alternatively, you can use the approach suggested by cynicalman:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template