suresh
suresh

Reputation: 417

Remove objects from ArrayList?

I have one ListView, it contains check boxes. By default all check boxes are checked, if we uncheck any check box the position will be added to mCheckedArrayList. Now I want remove all unchecked positions from the Listview. I used the following code:

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

But it is giving an ArrayIndexOutOfBounds exception.

Upvotes: 2

Views: 24057

Answers (5)

Moss
Moss

Reputation: 6012

You are removing objects in the wrong order. You should always reverse the order of the loop if you are removing elements within the loop:

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

As a side note, if you wanted to loop through front first (in cases where you are not deleting elements), you would have to change your loop end condition to the following:

i < mCheckedArrayList.size()

Thanks to Martín for the comment. To be aware of modifications you could always use a 'final ref' of the array.

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

Upvotes: 15

βhargavḯ
βhargavḯ

Reputation: 9836

No need to take any iterator. No need to loop your list to remove objects from list.

Following line will simply remove all objects from arraylist and makes it empty.

myArrayList.clear();

Upvotes: 4

Nikolay Ivanov
Nikolay Ivanov

Reputation: 8935

From my point of view using iterators is most correct part

ListIterator<Object> listIterator = mCheckedArray.listIterator();       
    for(;listIterator.hasNext() ; listIterator.next()){ 
        listIterator.remove();
    }

It'll also prevents another thread from injecting objects into yours collection

Upvotes: 2

Pete Houston
Pete Houston

Reputation: 15089

In programming, first item start at 0, last item is at the size minus 1.

for(int i=0;i<=mCheckedArrayList.size;i++){ // <-- remove '=' 

Upvotes: 0

rmp2150
rmp2150

Reputation: 807

Try changing '<=' in your for loop to '<'.

Upvotes: 0

Related Questions