Java use instanceof with iterator -


i have abstract class usuarioand arraylist<usuario> objects of 3 subclasses. want iterate through arraylist , return value depending of result of using instanceof against object.

i error: java.util.nosuchelementexception.

i suppose because of iterator being object of iterator , not of subclasses usuario. right? there solution that?

public int comprobardni(string dniacomprobar, arraylist<usuario> listausuarios) {     iterator<usuario> itusuarios = listausuarios.iterator();     while (itusuarios.hasnext()) {         if (dniacomprobar.equals(itusuarios.next().getdni())) {             if (itusuarios.next() instanceof usuariobiblioteca) {                 return 1;             } else if (itusuarios.next() instanceof bibliotecario) {                 return 2;             } else if (itusuarios.next() instanceof bibliotecaexterna) {                 return 3;             }         }     }     return 0; } 

you invoking itusuarios.next multiple times during iteration.

therefore might end invoking while list has been iterated fully, throw java.util.nosuchelementexception.

consider assigning usuario value once, , referring instead:

while (itusuarios.hasnext()) {   // reference instead of itusuarios.nex() next references   usuario usuario = itusuarios.next();  

or...

go fast enumeration cleaner looking code:

for (usuario usuario: listausuarios) {     ... 

Comments

Popular posts from this blog

matlab - error with cyclic autocorrelation function -

django - (fields.E300) Field defines a relation with model 'AbstractEmailUser' which is either not installed, or is abstract -

c# - What is a good .Net RefEdit control to use with ExcelDna? -