-1

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
  • 349,597
  • 67
  • 533
  • 578
Johnny Robertson
  • 117
  • 1
  • 3
  • 13
  • 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. –  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).

  • 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