从Java中的ArrayList删除对象 [英] Deleting objects from an ArrayList in Java

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

问题描述

我需要从删除某些对象的ArrayList 如果符合条件,我想知道哪种方式可能更有效。

I need to delete some objects from an ArrayList if they meet a condition and I'm wondering which way could be more efficient.

下面的情况:我有一个包含的ArrayList 包含一些其他对象的类。我不得不遍历这个的ArrayList 并删除会议一定条件的所有元素。
据我所知,这将是我的选择,删除:

Here's the situation: I have a class that contains an ArrayList containing some other objects. I have to iterate over this ArrayList and delete all elements meeting a certain condition. As far as I know, those would be my options to delete:


  1. 创建一个新的的ArrayList 并添加不符合条件的元素。迭代后,交换从旧的数组列表而不元素新的。

  1. Create a new ArrayList and add the elements that doesn't meet the condition. After the iteration, swap from the old arraylist to the new one without the elements.

创建一个新的的ArrayList 并添加满足条件的元素。迭代后,使用过的 ArrayList中的的removeAll()与要删除的对象。

Create a new ArrayList and add the elements that meet the condition. After the iteration, use the removeAll() method passing the ArrayList with the objects to be deleted.

有没有删除从对象更有效的方式的ArrayList

Is there a more efficient way to delete objects from an ArrayList?

推荐答案

另一种方式:迭代器有一个可选的remove() - 方法,即对ArrayList的实现。你可以使用它,而迭代。

Another way: The Iterator has an optional remove()-method, that is implemented for ArrayList. You can use it while iterating.

我不知道,虽然,这变种是最高效的,你应该衡量它。

I don't know though, which variant is the most performant, you should measure it.

starblue评论,这种复杂性是不好的,这是真的(为的removeAll()也是如此),因为ArrayList中有复制所有的元素,如果在中间是一个元素添加或删除。对于案件应在LinkedList更好地工作。但是,正如我们都不知道你真正用例的最好太测量所有变种,挑选最佳的解决方案。

starblue commented, that the complexity isn't good, and that's true (for removeAll() too), because ArrayList has to copy all elements, if in the middle is an element added or removed. For that cases should a LinkedList work better. But, as we all don't know your real use-cases the best is too measure all variants, to pick the best solution.

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

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