Question

I am programming in Java I have created a class to obtain one iterator since I'm only using one list in this program with this code

public ListIterator<T> iterateur() {
    ListIterator<T> it = liste.listIterator();
    return it;
}

And then I try to use it with this method

public int ObtenirNbElments(int priorite) {
    int nbPrio=0;
    while(this.iterateur().hasNext()){
        if(this.iterateur().next().obtenirPriorite() == priorite){
            nbPrio++;
        }
    }
    return nbPrio;
}

Whenever I use it with my test class as such:

    listePriorite.ajouter(elt1);
    listePriorite.ajouter(elt2);
    listePriorite.ajouter(elt3);
    listePriorite.ajouter(elt4);
    listePriorite.ajouter(eltd1);
    assertEquals(2,listePriorite.ObtenirNbElments(1));

It seems to enter into an infinite loop why is that?

Was it helpful?

Solution

Every time you invoke iterateur() you create and return a new ListIterator. Call the method only once and store the result. Re-use the same object.

int nbPrio=0;
ListIterator<T> it = this.iterateur();
while(it.hasNext()){
    if(it.next().obtenirPriorite() == priorite){
        nbPrio++;
    }
}
return nbPrio;

(I'm assuming your T has bounds that make sense with obtenirPriorite().)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top