Android – delete objects from ArrayList?

I have a listview. By default, my listview contains check boxes and all selected check boxes. If we uncheck any check box and add it to the location of mcheckedarraylist. I, to delete all unchecked locations from the listview. I, use the following code,

for(int i=0;i<=mCheckedArrayList.size;i++){
    int removePosition=mCheckedArrayList.get(i);
    mDisplayArrayList.remove(removePosition);
}

It gives arrayindexoutofbounds exception.pls to help me

resolvent:

You are deleting objects in the wrong order. If you want to delete elements in a loop, you should always reverse the order of the loop:

for(int i = mCheckedArrayList.size()-1 ; i >= 0; i--){
    mDisplayArrayList.remove(mCheckedArrayList.get(i));
}

As a side note, if you want to traverse the front first (if you don't delete the element), you must change the loop end condition to the following:

i < mCheckedArrayList.size()

Thanks for mart í n's comments. To understand the changes, you can always use the "final reference" of the array

final ArrayList<T> arrayListToBeUsed = mCheckedArrayList;
for(int i = arrayListToBeUsed .size()-1 ; i >= 0; i--){
    arrayListToBeUsed .remove(arrayListToBeUsed .get(i));
}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>