I have array of objects how to iterate throw this array and delete some objects depending on the condition:

ArrayList<Book>b=new ArrayList<Book>();
for(int i = 0 ; i < b.size ; i ++){
//if some condition
//remove b.get(i);
}

what should I do??

  1. You can use b.remove(i) to remove entries. Loop down from the end of the list to the beginning to avoid confusing your loop's indexing when you delete an entry

  2. You can't use any ordinary iterator because they don't allow you to change the List while iterating.
    But...
    a ListIterator allows you to update & delete while iterating. You get one simply by b.listIterator() then use it as described in the API doc.

can you explain b.listIterato a bit more?!thanks

do you mean:

    b.listIterator(i).remove();

i look at but I do not understand

OK. In that case why not go back to solution 1, that doesn't involve any new classes or concepts.

thank you:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.