NewDroidDev
NewDroidDev

Reputation: 1686

How to delete data in ArrayList using a for loop

I'm deleting my ArrayList data using for loop but the loop only deletes the last index of my list. What's wrong with this? I think this would be easy but I'm taking an hour an still cannot solve this.

 for (int i = 0; i < selectedRowFile.size() - 1; i++) {
     imagesFileName.remove(i);
         mylist.remove(i);
     adapter.notifyDataSetChanged();
     Toast.makeText(getApplicationContext(),"" + selectedRowFile.size() , Toast.LENGTH_LONG).show();
}

Upvotes: 0

Views: 363

Answers (2)

Steve Benett
Steve Benett

Reputation: 12933

You should remove an element from a List using an Iterator.

        Iterator<YourDataType> it = YourList.iterator();
        while (it.hasNext()) 
               it.remove();

With this you can use if-else to specify the element, which should be removed.

This should give you some hints, why you should use an Iterator.

Upvotes: 4

JREN
JREN

Reputation: 3630

I don't know why you're using a for loop, but you can also clear an ArrayList object by using clear.

List myList = new ArrayList<Object>();
myList.clear();

Using a for loop to clear an ArrayList seems dubious to me.

Upvotes: 2

Related Questions