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

查看:24
本文介绍了在 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,添加不符合条件的元素.迭代后,从旧的arraylist 交换到没有元素的新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,添加符合条件的元素.迭代后,使用removeAll() 方法传递ArrayList 和要删除的对象.

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天全站免登陆