Java iterator.hasNext() is always true

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

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();      } } 

回答1:

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();     ... 


回答2:

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

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!