Alucard
Alucard

Reputation: 317

Java iterator.hasNext() is always true

I have a little problem with the code as seen below. The iterator().hasNext() will never turn into false because the next() function always returns the same element. It ends in an infinite loop.

I would like to set the attribute UserLock in every element in the collection (returned from GetElements()). If the type of the element is "Package", I will lock all elements under the package with a recursive call of the lockAllElements function.

private void lockAllElements(String internalGUID) {
    Element tempElem = null;

    while((repo.GetPackageByGuid(internalGUID).GetElements().iterator().hasNext()) == true) {
        tempElem = repo.GetPackageByGuid(internalGUID).GetElements().iterator().next();

        if(tempElem.GetType().equals("Package")) {                
            this.lockAllElements(tempElem.GetElementGUID());
        }

        tempElem.ApplyUserLock(); 
    }
}

Upvotes: 5

Views: 9339

Answers (2)

lance-java
lance-java

Reputation: 27966

Following on from @Eran's answer... I sometimes prefer a for loop:

for (Iterator<Element> iter = repo.GetPackageByGuid(internalGUID).GetElements().iterator(); iter.hasNext(); ) {
    tempElem = iter.next();
}

Upvotes: 3

Eran
Eran

Reputation: 393771

It is always true because you get a new Iterator instance in each iteration of your loop. You should get a single Iterator instance and use that instance throughout the loop.

Change

while((repo.GetPackageByGuid(internalGUID).GetElements().iterator().hasNext()) == true) {
    tempElem = repo.GetPackageByGuid(internalGUID).GetElements().iterator().next();
    ...

to

Iterator<Element> iter = repo.GetPackageByGuid(internalGUID).GetElements().iterator();
while(iter.hasNext()) {
    tempElem = iter.next();
    ...

Upvotes: 19

Related Questions