Deleting objects from an ArrayList in Java

前端 未结 13 1844
轮回少年
轮回少年 2020-12-15 03:14

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

Here\'s the situation: I

13条回答
  •  时光说笑
    2020-12-15 04:08

    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 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.

提交回复
热议问题