Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove items from generic arraylist in Android (Java)

Tags:

java

android

I have a generic arraylist of an object here I want to remove certain elements, The problem is when I iterate the list with for loop, I can't do a simple sequence of remove()'s because the elements are shifted after each removal.

Thanks

like image 641
Rakshi Avatar asked Dec 01 '22 05:12

Rakshi


2 Answers

Use Iterator to remove element

Like

Iterator itr = list.iterator();
String strElement = "";
while (itr.hasNext()) {
    strElement = (String) itr.next();
    if (strElement.equals("2")) {
        itr.remove();
    }
}
  • See here
like image 158
Samir Mangroliya Avatar answered Dec 02 '22 20:12

Samir Mangroliya


You can iterate the list this way ...

public void clean(List<Kopek> kopeks) {
  for(Kopek kopek : kopeks) {
    if (kopek.isDirty())
      kopeks.remove(kopek);
  }
}

Which is equiv to ...

public void clean1(List<Kopek> kopeks) {
  Iterator<Kopek> kopekIter = kopeks.iterator();

  while (kopekIter.hasNext()) {
    Kopek kopek = kopekIter.next();
    if (kopek.isDirty())
      kopeks.remove(kopek);
  }
}

Don't do this ... (due to the reason you have already observed.)

public void clean(List<Kopek> kopeks) {
  for(int i=0; i<kopeks.size(); i++) {
    Kopek kopek = kopeks.get(i);
    if (kopek.isDirty())
      kopeks.remove(i);
  }
}

However, I believe removal by index rather than by object is more efficient. Removal by object is not efficient because the list is in most cases not a hashed list.

kopeks.remove(kopek);

vs

kopeks.remove(i);

To achieve positional remove, by treating a moving target appropriately ...

public void clean(List<Kopek> kopeks) {
  int i=0;
  while(i<kopeks.size()) {
    Kopek kopek = kopeks.get(i);
    if (kopek.isDirty()) // no need to increment.
      kopeks.remove(i);
    else
      i++;
  }
}
like image 20
Blessed Geek Avatar answered Dec 02 '22 19:12

Blessed Geek