简体   繁体   中英

Iterator.hasNext() does not appear to return false on the last item in a List

I have an if-else function within a for loop iterating through a list. When I reach the last element of this list, I want it to undertake an action, but it doesn't seem to be working. Here is an outline of my code:

for(Item t: itemList){
    if(....){
         }
    else if(....){
         }
    else if(currentStartTime>previousFinishTime){
         System.out.println("C");
         if(itemList.iterator().hasNext()==false){
                System.out.println("end of array");
                EFTs.add(EFT);}  
    else{.....;}
      }

When I trigger this condition with the last item in the list (ie the last item has currentStartTime>previousFinishTime, I know this is correct because it prints C ), nothing in my if condition triggers. Have I misunderstood the purpose of the hasNext() function?

Thanks

itemList.iterator().hasNext()==false

itemList.iterator() refers to a brand new iterator. It doesn't refer to the iterator being used in the for loop. itemList.iterator() will in fact always start at the beggining of the list, and thus hasNext() will tell you if the list is empty.

To use an iterator like this, you need to make your own loop, something like:

for(Iterator<Item> iter = itemList.iterator(); iter.hasNext(); ) {
    Item item = iter.next();
    if(iter.hasNext()) {
    }
}

But 95% of the time, you should be able to do whatever you want after the loop instead of during the last iteration.

With the "enhanced for", you cannot access the operator created for the for operation.

What you are doing is creating a new operator each time, so it points to the start of the list. Obviously, unless it is an empty list, it will return true for hasNext() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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