Trival
Trival

Reputation: 583

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?

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:

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

Upvotes: 0

Views: 2770

Answers (2)

zibi
zibi

Reputation: 3313

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

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

which will return true always when there's at least one element.

Calling iterator() always return new iterator, you should probably use the one provided in the parameter.

Upvotes: 2

Ryan Stewart
Ryan Stewart

Reputation: 128779

The only hasNext() I see is 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.

Upvotes: 1

Related Questions