Java iterator.hasNext()始终为true [英] Java iterator.hasNext() is always true
问题描述
我的代码有点问题,如下所示。 iterator()。hasNext()
永远不会变为false,因为 next()
函数总是返回相同的元素。它以无限循环结束。
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.
我想在集合中的每个元素中设置属性UserLock(从<$ c $返回) C>的getElements())。
如果元素的类型是Package,我将使用lockAllElements函数的递归调用锁定包下的所有元素。
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();
}
}
推荐答案
它总是如此,因为你在循环的每次迭代中得到一个新的 Iterator
实例。您应该获得一个 Iterator
实例并在整个循环中使用该实例。
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.
更改
while((repo.GetPackageByGuid(internalGUID).GetElements().iterator().hasNext()) == true) {
tempElem = repo.GetPackageByGuid(internalGUID).GetElements().iterator().next();
...
到
Iterator<Element> iter = repo.GetPackageByGuid(internalGUID).GetElements().iterator();
while(iter.hasNext()) {
tempElem = iter.next();
...
这篇关于Java iterator.hasNext()始终为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!