从数组中删除元素 (Java)

发布于 2024-07-14 22:40:57 字数 39 浏览 4 评论 0原文

在 Java 中是否有任何快速(且美观)的方法从数组中删除元素?

Is there any fast (and nice looking) way to remove an element from an array in Java?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

别挽留 2024-07-21 22:40:57

您可以使用 commons lang 的 ArrayUtils。

array = ArrayUtils.removeElement(array, element)

commons.apache.org库:Javadocs

You could use commons lang's ArrayUtils.

array = ArrayUtils.removeElement(array, element)

commons.apache.org library:Javadocs

手心的温暖 2024-07-21 22:40:57

你的问题不是很清楚。 从您自己的回答中,我可以更好地告诉您您正在尝试做什么:

public static String[] removeElements(String[] input, String deleteMe) {
    List result = new LinkedList();

    for(String item : input)
        if(!deleteMe.equals(item))
            result.add(item);

    return result.toArray(input);
}

注意:这是未经测试的。 错误检查留给读者作为练习(如果 inputdeleteMe 为 null,我会抛出 IllegalArgumentException;null 上的空列表列表输入没有意义。从数组中删除空字符串可能有意义,但目前我也将其作为练习,当它尝试调用 equals 时,它会抛出一个 NPE 。 deleteMe 如果 deleteMe 为 null。)

我在这里所做的选择:

我使用了 LinkedList。 迭代应该同样快,并且如果最终删除大量元素,则可以避免任何调整大小或分配太大的列表。 您可以使用 ArrayList,并将初始大小设置为输入的长度。 这可能不会产生太大影响。

Your question isn't very clear. From your own answer, I can tell better what you are trying to do:

public static String[] removeElements(String[] input, String deleteMe) {
    List result = new LinkedList();

    for(String item : input)
        if(!deleteMe.equals(item))
            result.add(item);

    return result.toArray(input);
}

NB: This is untested. Error checking is left as an exercise to the reader (I'd throw IllegalArgumentException if either input or deleteMe is null; an empty list on null list input doesn't make sense. Removing null Strings from the array might make sense, but I'll leave that as an exercise too; currently, it will throw an NPE when it tries to call equals on deleteMe if deleteMe is null.)

Choices I made here:

I used a LinkedList. Iteration should be just as fast, and you avoid any resizes, or allocating too big of a list if you end up deleting lots of elements. You could use an ArrayList, and set the initial size to the length of input. It likely wouldn't make much of a difference.

泛泛之交 2024-07-21 22:40:57

最好的选择是使用集合,但如果由于某种原因无法使用集合,请使用 arraycopy。 您可以使用它以稍微不同的偏移量从同一个数组复制或复制到同一个数组。

例如:

public void removeElement(Object[] arr, int removedIdx) {
    System.arraycopy(arr, removedIdx + 1, arr, removedIdx, arr.length - 1 - removedIdx);
}

编辑回应评论:

这不是另一种好方法,它实际上是唯一可接受的方法 - 任何允许此功能的工具(如 Java.ArrayList 或 apache utils)都将在幕后使用此方法。 另外,你真的应该使用ArrayList(或者链接列表,如果你从中间删除很多),所以这甚至不应该是一个问题,除非你把它作为家庭作业来做。

要分配一个集合(创建一个新数组),然后删除一个元素(集合将使用 arraycopy 执行此操作),然后在其上调用 toArray (创建第二个新数组),每次删除都会使我们达到这不是一个优化问题的地步,这是极其糟糕的编程。

假设您有一个阵列占用 100MB 的内存。 现在您想要迭代它并删除 20 个元素。

尝试一下......

我知道你认为它不会那么大,或者如果你一次删除那么多,你会以不同的方式编码,但我已经修复了很多有人制作的代码诸如此类的假设。

The best choice would be to use a collection, but if that is out for some reason, use arraycopy. You can use it to copy from and to the same array at a slightly different offset.

For example:

public void removeElement(Object[] arr, int removedIdx) {
    System.arraycopy(arr, removedIdx + 1, arr, removedIdx, arr.length - 1 - removedIdx);
}

Edit in response to comment:

It's not another good way, it's really the only acceptable way--any tools that allow this functionality (like Java.ArrayList or the apache utils) will use this method under the covers. Also, you REALLY should be using ArrayList (or linked list if you delete from the middle a lot) so this shouldn't even be an issue unless you are doing it as homework.

To allocate a collection (creates a new array), then delete an element (which the collection will do using arraycopy) then call toArray on it (creates a SECOND new array) for every delete brings us to the point where it's not an optimizing issue, it's criminally bad programming.

Suppose you had an array taking up, say, 100mb of ram. Now you want to iterate over it and delete 20 elements.

Give it a try...

I know you ASSUME that it's not going to be that big, or that if you were deleting that many at once you'd code it differently, but I've fixed an awful lot of code where someone made assumptions like that.

终遇你 2024-07-21 22:40:57

您无法从基本 Java 数组中删除元素。 看看各种 Collections 和 ArrayList 吧。

You can't remove an element from the basic Java array. Take a look at various Collections and ArrayList instead.

时光病人 2024-07-21 22:40:57

看起来不错的解决方案是首先使用列表而不是数组。

List.remove(index)

如果您必须使用数组,则两次调用System.arraycopy很可能是最快的。

Foo[] result = new Foo[source.length - 1];
System.arraycopy(source, 0, result, 0, index);
if (source.length != index) {
    System.arraycopy(source, index + 1, result, index, source.length - index - 1);
}

Arrays.asList 也是处理数组的不错选择,但它似乎不支持remove。)

Nice looking solution would be to use a List instead of array in the first place.

List.remove(index)

If you have to use arrays, two calls to System.arraycopy will most likely be the fastest.

Foo[] result = new Foo[source.length - 1];
System.arraycopy(source, 0, result, 0, index);
if (source.length != index) {
    System.arraycopy(source, index + 1, result, index, source.length - index - 1);
}

(Arrays.asList is also a good candidate for working with arrays, but it doesn't seem to support remove.)

尐偏执 2024-07-21 22:40:57

我认为问题是要求一个不使用 Collections API 的解决方案。 人们使用数组来处理低级细节(性能很重要),或者用于松散耦合的 SOA 集成。 在后面,可以将它们转换为集合并将它们传递给业务逻辑。

对于低级性能的东西,它通常已经被 for 循环等快速而肮脏的命令式状态混合所混淆。在这种情况下,在集合和数组之间来回转换是麻烦的、不可读的,甚至是资源密集型的。

顺便问一下,TopCoder,有人吗? 总是那些数组参数! 因此,请做好在竞技场中应对它们的准备。

以下是我对问题的解释以及解决方案。 它在功能上与 Bill Kjelovirt。 此外,它还可以优雅地处理元素不在数组中的情况。

希望有帮助!

public char[] remove(char[] symbols, char c)
{
    for (int i = 0; i < symbols.length; i++)
    {
        if (symbols[i] == c)
        {
            char[] copy = new char[symbols.length-1];
            System.arraycopy(symbols, 0, copy, 0, i);
            System.arraycopy(symbols, i+1, copy, i, symbols.length-i-1);
            return copy;
        }
    }
    return symbols;
}

I think the question was asking for a solution without the use of the Collections API. One uses arrays either for low level details, where performance matters, or for a loosely coupled SOA integration. In the later, it is OK to convert them to Collections and pass them to the business logic as that.

For the low level performance stuff, it is usually already obfuscated by the quick-and-dirty imperative state-mingling by for loops, etc. In that case converting back and forth between Collections and arrays is cumbersome, unreadable, and even resource intensive.

By the way, TopCoder, anyone? Always those array parameters! So be prepared to be able to handle them when in the Arena.

Below is my interpretation of the problem, and a solution. It is different in functionality from both of the one given by Bill K and jelovirt. Also, it handles gracefully the case when the element is not in the array.

Hope that helps!

public char[] remove(char[] symbols, char c)
{
    for (int i = 0; i < symbols.length; i++)
    {
        if (symbols[i] == c)
        {
            char[] copy = new char[symbols.length-1];
            System.arraycopy(symbols, 0, copy, 0, i);
            System.arraycopy(symbols, i+1, copy, i, symbols.length-i-1);
            return copy;
        }
    }
    return symbols;
}
暗地喜欢 2024-07-21 22:40:57

您可以使用 ArrayUtils API以“美观的方式”删除它。 它在数组上实现了许多操作(删除、查找、添加、包含等)。
看一看。 它让我的生活变得更简单。

You could use the ArrayUtils API to remove it in a "nice looking way". It implements many operations (remove, find, add, contains,etc) on Arrays.
Take a look. It has made my life simpler.

静若繁花 2024-07-21 22:40:57

好的,非常感谢
现在我用这样的东西:

public static String[] removeElements(String[] input, String deleteMe) {
    if (input != null) {
        List<String> list = new ArrayList<String>(Arrays.asList(input));
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).equals(deleteMe)) {
                list.remove(i);
            }
        }
        return list.toArray(new String[0]);
    } else {
        return new String[0];
    }
}

okay, thx a lot
now i use sth like this:

public static String[] removeElements(String[] input, String deleteMe) {
    if (input != null) {
        List<String> list = new ArrayList<String>(Arrays.asList(input));
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).equals(deleteMe)) {
                list.remove(i);
            }
        }
        return list.toArray(new String[0]);
    } else {
        return new String[0];
    }
}
情绪少女 2024-07-21 22:40:57

Bill K 和 dadinn 编写的内容还需要一些更多的先决条件

Object[] newArray = new Object[src.length - 1];
if (i > 0){
    System.arraycopy(src, 0, newArray, 0, i);
}

if (newArray.length > i){
    System.arraycopy(src, i + 1, newArray, i, newArray.length - i);
}

return newArray;

Some more pre-conditions are needed for the ones written by Bill K and dadinn

Object[] newArray = new Object[src.length - 1];
if (i > 0){
    System.arraycopy(src, 0, newArray, 0, i);
}

if (newArray.length > i){
    System.arraycopy(src, i + 1, newArray, i, newArray.length - i);
}

return newArray;
天煞孤星 2024-07-21 22:40:57

您无法更改数组的长度,但可以通过复制新值并将其存储到现有索引号来更改索引保存的值。
1=mike , 2=jeff // 10 = george 11 转到 1 覆盖 mike 。

Object[] array = new Object[10];
int count = -1;

public void myFunction(String string) {
    count++;
    if(count == array.length) { 
        count = 0;  // overwrite first
    }
    array[count] = string;    
}

You can not change the length of an array, but you can change the values the index holds by copying new values and store them to a existing index number.
1=mike , 2=jeff // 10 = george 11 goes to 1 overwriting mike .

Object[] array = new Object[10];
int count = -1;

public void myFunction(String string) {
    count++;
    if(count == array.length) { 
        count = 0;  // overwrite first
    }
    array[count] = string;    
}
纸伞微斜 2024-07-21 22:40:57

将原始数组复制到另一个数组中,不删除要删除的元素。

更简单的方法是使用 List、Set... 并使用 remove() 方法。

Copy your original array into another array, without the element to be removed.

A simplier way to do that is to use a List, Set... and use the remove() method.

背叛残局 2024-07-21 22:40:57

如果不感兴趣缩小数组大小,则将要删除的项目与最后一个项目交换。

Swap the item to be removed with the last item, if resizing the array down is not an interest.

救赎№ 2024-07-21 22:40:57

我希望你使用java集合/java commons集合!

使用 java.util.ArrayList 您可以执行以下操作:

yourArrayList.remove(someObject);

yourArrayList.add(someObject);

I hope you use the java collection / java commons collections!

With an java.util.ArrayList you can do things like the following:

yourArrayList.remove(someObject);

yourArrayList.add(someObject);
北斗星光 2024-07-21 22:40:57

使用ArrayList

alist.remove(1); //removes the element at position 1

Use an ArrayList:

alist.remove(1); //removes the element at position 1
城歌 2024-07-21 22:40:57

当然,创建另一个数组:)

Sure, create another array :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文