Remove objects from an ArrayList based on a given

2020-02-05 13:02发布

I would like to remove an element from an ArrayList in Java if it meets a certain criteria.

ie:

for (Pulse p : pulseArray) {
    if (p.getCurrent() == null) {
        pulseArray.remove(p);
    }
}

I can understand why this does not work, but what is a good way to do this?

7条回答
我命由我不由天
2楼-- · 2020-02-05 13:32

When you are removing the element from the same list, the index gets disturbed. Try little differently as below:

  for (int i=0; i < pulseArray.size(); i++) {
     Pulse p = (Pulse)pulseArray.get(i);
     if (p.getCurrent() == null) {
        pulseArray.remove(p);
        i--;//decrease the counter by one
     }
  }
查看更多
登录 后发表回答