如何从 Java 中的数组中删除对象? [英] How do I remove objects from an array in Java?

查看:40
本文介绍了如何从 Java 中的数组中删除对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个n对象数组,假设它是一个字符串数组,它有以下值:

Given an array of n Objects, let's say it is an array of strings, and it has the following values:

foo[0] = "a";
foo[1] = "cc";
foo[2] = "a";
foo[3] = "dd";

如何删除/移除数组中与 "a" 相等的所有字符串/对象?

What do I have to do to delete/remove all the strings/objects equal to "a" in the array?

推荐答案

[如果你想要一些现成的代码,请滚动到我的Edit3"(剪切后).其余的留给后代.]

[If you want some ready-to-use code, please scroll to my "Edit3" (after the cut). The rest is here for posterity.]

充实Dustman的想法:

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

我现在使用 Arrays.asList 而不是 Collections.singleton:单例仅限于一个条目,而 asList方法允许您添加其他字符串以供稍后过滤:Arrays.asList("a", "b", "c").

I'm now using Arrays.asList instead of Collections.singleton: singleton is limited to one entry, whereas the asList approach allows you to add other strings to filter out later: Arrays.asList("a", "b", "c").

Edit2:上面的方式保留了相同的数组(所以数组还是一样的长度);最后一个之后的元素设置为空.如果你想要一个 new 数组的大小完全符合要求,请改用这个:

The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a new array sized exactly as required, use this instead:

array = list.toArray(new String[0]);

<小时>

Edit3:如果您在同一个类中频繁使用此代码,您可能希望将其添加到您的类中:


If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class:

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

那么函数就变成了:

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

这将停止用无用的空字符串数组乱扔堆,否则每次调用函数时都会new.

This will then stop littering your heap with useless empty string arrays that would otherwise be newed each time your function is called.

愤世嫉俗者的建议(见评论)也将有助于堆乱抛垃圾,为了公平起见,我应该提到它:

cynicalman's suggestion (see comments) will also help with the heap littering, and for fairness I should mention it:

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

我更喜欢我的方法,因为它可能更容易弄错显式大小(例如,在错误的列表中调用 size()).

I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling size() on the wrong list).

这篇关于如何从 Java 中的数组中删除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆