0

I need to iterate through an arrayList and add/remove elemets from it based on some conditions. The issue is that after adding/removing the arrayList's size changes and therefore I get a Null Pointer Exception error. Any help would be appreciated.

 public class hello{
   MyArrayList<Integer> list = new MyArrayList<>();
   list.add(1);
   list.add(2);
   .......
   for (int i = 0; i < list.size(); i++){
       if(//some condition){
          list.add(//something);
       }
       else if(//some condition){
           list.remove(//something);

      }
    }
 }
Bababooey
  • 13
  • 3

3 Answers3

0

Assuming your MyArrayList class extends ArrayList, you could use a ListIterator to traverse the list and add/remove elements.

https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html

Travis Cook
  • 161
  • 9
0

You should use a foreach loop. That way, you will iterate through every single element of your list regardless of size changing if you add or remove elements.

Here's an example :

for(Integer number : list) {
    if(number <= 1){
        list.remove(number);
    }
    else if(number >= 3) {
        list.add(number + 1);
    }
}
TiGaube
  • 31
  • 1
0

You also can use Stream API and iterate through all elements with filter or map like below :

list.stream().filter(a->"some condition").map(a-> "some mapping").collect("some collector")