简体   繁体   English

Iterator.hasNext()在列表中的最后一项上似乎未返回false

[英]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. 我在循环遍历列表的for循环中有一个if-else函数。 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. 当我用列表中的最后一项触发此条件时(即,最后一项具有currentStartTime> previousFinishTime,我知道这是正确的,因为它显示C ),如果条件条件触发,则没有任何结果。 Have I misunderstood the purpose of the hasNext() function? 我是否误解了hasNext()函数的用途?

Thanks 谢谢

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

itemList.iterator() refers to a brand new iterator. itemList.iterator()引用一个全新的迭代器。 It doesn't refer to the iterator being used in the for loop. 它没有引用for循环中使用的迭代器。 itemList.iterator() will in fact always start at the beggining of the list, and thus hasNext() will tell you if the list is empty. itemList.iterator()实际上总是从列表的开头开始,因此hasNext()会告诉您列表是否为空。

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. 但是有95%的时间,您应该能够在循环之后而不是在上一次迭代期间执行所需的任何操作。

With the "enhanced for", you cannot access the operator created for the for operation. 使用“增强的”,您将无法访问为for操作创建的操作员。

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() . 显然,除非它是一个空列表,否则它将为hasNext()返回true

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

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