Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); 
    }
}
like image 987
Alucard Avatar asked Sep 09 '15 06:09

Alucard


2 Answers

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();
    ...
like image 74
Eran Avatar answered Sep 29 '22 06:09

Eran


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();
}
like image 21
lance-java Avatar answered Sep 29 '22 08:09

lance-java