gmlyranetwork
gmlyranetwork

Reputation: 91

List java do not work on loop

I have a list of items and in a for loop i'm trying to compare this list but the list make ArrayOutOfBoundsException.

Out of the for loop the list has 4 items (0,1,2,3) but in the for have only 3 (0,1,2) when I try to access the last item an exception is raised.

List<Relatorio> relatorios = new RelatorioDao().listaTudoEmpresa(userWeb.logado);
        for(int i = 0; i < relatorios.size(); i++){
            if(!contem(relatorios.get(i))){
                relatorios.remove(i);
            }
        }

Upvotes: 0

Views: 111

Answers (3)

Romain Hippeau
Romain Hippeau

Reputation: 24375

You cannot do a delete on an item in a list as you are iterating through it. You must use the remove that is on the iterator to do so.
See This post.

Upvotes: 0

Alexander Pogrebnyak
Alexander Pogrebnyak

Reputation: 45576

You should not remove items from non-iterator loop.

Consider doing this instead

for( Iterator<Realtorio> iter = realtorios.iterator( ); iter.hasNext( ); )
{
   Relatorio cur = iter.next( );

   if(!contem(cur)){
      iter.remove( );
   }
}

Upvotes: 2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

That's because when you remove the element, you make the list size smaller, thus shortening the loop.

Use the dedicated list iterator when you want to remove elements while iterating, it is safe for this operation :

    Iterator<Relatorio> it = relatorios.iterator();
    while (it.hasNext())
        if (...) {
            it.remove();
        }
    }

Upvotes: 2

Related Questions