0

I want to delete Even numbers from arrayList , my code works fine as in i can add and print values of the arrayList. However when i want to loop through the ArrayList and delete even numbers i get stuck. This is what i have come up with so far but dont know where to go forward

for (int i = 0; i < userNumber.size(); i++) {
    System.out.println(userNumber.get(i));
    if (userNumber(i) % 2 == 0) {
        //
    }
}       

I was thinking that if the remainder of the number is 0 on each index of the Arraylist, then we can use the userNumber.remove(); Not sure how to implement that however..

MC Emperor
  • 20,870
  • 14
  • 76
  • 119
  • Well, one can remove an `ArrayList` element with the `remove` method. However, removing an element while looping causes the `ArrayList` to shrink, so all indexes will change. You need to account for that. Alternatively, you could get an `Iterator` using the `ArrayList`'s `iterator()` method, and then call `Iterator`'s `remove()` method, which automatically accounts for the size change. – MC Emperor May 09 '22 at 19:20

0 Answers0