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

查看:274
本文介绍了如何从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";

什么我需要做删除/删除所有字符串/对象等于数组中?

推荐答案

[如果你想要一些准备使用的code,请滚动到我的EDIT3(切后)。其余的是在这里为后人。]

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

要充实清洁工的想法

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

编辑:现在,我使用 Arrays.asList 而不是 Col​​lections.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:上述方法保留了相同的阵列(以使阵列仍具有相同的长度);在最后的元素设置为null。如果你想要一个的新的的数组大小完全一样需要用这个来代替:

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:如果您使用在同一类频繁地对这个code,您不妨考虑将其加入你的类:


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);

这将然后停止无用的空字符串数组,否则将乱丢垃圾的堆 ED每个函数被调用时。

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

cynicalman的建议(见评论)也将与堆乱抛垃圾的帮助,并为公平我应该提到它:

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

我preFER我的做法,因为它可能会更容易得到明确的大小错误的(例如,呼叫尺寸()错误列表)。

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

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