简体   繁体   English

iterator.hasNext()返回错误的值

[英]iterator.hasNext() returns wrong value

I'm trying to use a an iterator in a recursive method. 我正在尝试在递归方法中使用迭代器。 It should exit the method if there is no next element left in the list. 如果列表中没有下一个元素,则应退出该方法。 But if the cursor are at the last position the check with iterator.hasNext() return true , I except false ? 但是,如果光标位于最后一个位置,则使用iterator.hasNext()返回的检查结果为true ,除了false以外,我是否还这样做?

Any ideas and hints? 有什么想法和提示吗?

I'm not albe to post image so I will write it down. 我不是要张贴图片,所以我会写下来。 That's what I'm seeing in the Eclipse-Debugger-View: 这就是我在Eclipse-Debugger-View中看到的:

iterator             | AbstractList$Itr (id=448)

 - cursor            | 2
 - excpectedModCount | 2
 - lastRet           | 1
 - this$0            | ArrayList<E> (id=438)
 - elemtData         | Object[10] (id=462)

 ---modCount         | 2

 ---size             | 2

Here's the code 这是代码

static void resolveWithIterator(List<SomethingContext> list, Iterator<ContextResolveHelper> iterator, List<ContextResolveHelper> resolverList)
{
    boolean end = resolverList.iterator().hasNext();
    if (list.size() == 1 || !end){
        resolvedList.add(list);
        return;
    }else{
        ContextResolveHelper acutalEntry = iterator.next();
    List<SomethingContext> tempQRes2 = new ArrayList<SomethingContext>();
        for (SomethingContext smtCtx : list){
            if (//check various things){
                tempQRes2.add(smtCtx);
            }
        }
        resolveWithIterator(tempQRes2, iterator, resolverList);
    }
}

I think the problem is in the logic itself, as you wrote, you call the function with: 我认为问题出在逻辑本身,正如您所写的那样,您使用以下命令调用该函数:

Iterator<ContextResolveHelper> iterator = resolverList.iterator();    
resolveWithIterator(searchCtxResult, iterator, resolverList);

but, in the method itself you do 2 separate things, you check next on new iterator, not the provided one 但是,在方法本身中,您要做2件事,请在新的迭代器上检查下一步,而不是在提供的迭代器上

boolean end = resolverList.iterator().hasNext();

which will return true always when there's at least one element. 当至少有一个元素时,它将始终返回true。

Calling iterator() always return new iterator, you should probably use the one provided in the parameter. 调用iterator()总是返回新的迭代器,您应该使用参数中提供的迭代器。

The only hasNext() I see is resolverList.iterator().hasNext() . 我看到的唯一hasNext()resolverList.iterator().hasNext() Since you get a new iterator every time, of course it will always have a "next", unless the list itself is empty. 由于每次都会有一个新的迭代器,因此,除非列表本身为空,否则它将始终有一个“下一个”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM