0

I have an arraylist like this:

ArrayList<Integer> numbers = new ArrayList<Integer>();

And let's say the values inside are like:

[0,1,2,3,4,5]

So I'm looping through and I want to remove values from the arraylist while I'm looping through:

for(int i=0; i<numbers.size();i++){
    if(numbers.get(i)>2){
    numbers.remove(i);
    }
}

How would I do this?

John Kugelman
  • 330,190
  • 66
  • 504
  • 555
Johnny Robertson
  • 127
  • 1
  • 11
  • I would consider creating a new list (copy) containing only the wanted values. It is so much safer. Of course, unless the list is very, very huge. – Michal Nov 27 '20 at 18:00
  • 1
    I'd say the exact opposite: removing elements becomes much less efficient on huge lists; it depends on n^2 while creating a list is n. – tibetiroka Nov 27 '20 at 18:34

1 Answers1

3

You can call numbers.remove(i) and then decrement i to follow the change in the position within the list: numbers.remove(i); i--;.

If you use iterators, foreach or the : operator you can't remove values, because they use unmodifiable lists.

If you have a simple way of determining whether a number should be removed, you can use numbers.removeIf((number)->number>2) (like the problem in your example).

tibetiroka
  • 1,065
  • 2
  • 11
  • 17
  • thank you so much! that i--; call was genius! I'm glad I posted a new question. thanks for posting an answer (a different and much better one) instead of referring me to the other one – Johnny Robertson Nov 27 '20 at 18:04