Iterator hasNext用于获取最后一条记录。

huangapple go评论58阅读模式
英文:

Iterator hasNext for the last record fetching

问题

private static void printList(LinkedList<String> linkedList) 
{
    Iterator<String> i = linkedList.iterator();

    while(i.hasNext()) 
    {
        System.out.println(i.next());
    }

    System.out.println("-------------------");
}

根据我的理解,`i.hasNext()` 方法用于检查是否存在下一个条目返回 truefalse

而上面的 `i.next()` 方法会显示当前的 linkedList 记录然后递增/移动到下一个记录

如果我们在最后一条记录,`i.hasNext()`false为什么它还会执行最后一次 `i.next()` 迭代
英文:
private static void printList(LinkedList&lt;String&gt; linkedList) 
{
        Iterator&lt;String&gt; i = linkedList.iterator();

        while(i.hasNext()) 
        {
            System.out.println(i.next());
        }

        System.out.println(&quot;-------------------&quot;);
}

As per my understanding, i.hasNext() method checks whether the next entry exists or not and returns true or false.

And the i.next() method above here, will display the current linkedList record and then increments/moves to the next record.

If we are in the last record, i.hasNext() is false, how is it still executing the last iteration of i.next()?

答案1

得分: 3

好的,以下是翻译好的内容:

假设你的列表是 1, 2, 3, 4

当迭代器的 hasNext() 在开始时返回 true,因为它当前指向开头,而下一个元素是 1。通过 i.next(),你会得到 1

现在,在倒数第二次迭代时,当光标位于 3 处并且你已通过 i.next() 得到了 3。此时 i.hasNext() 会返回 true,因为还有元素 4,你将会进入循环,并执行 i.next() 来消耗整个列表,因此接下来对 i.hasNext() 的调用将返回 false,从而终止循环。

英文:

So say you have your list as 1, 2, 3, 4

Your iterator hasNext() will return true when it will start since it's currently pointing to the start and next has 1 in it. With i.next(), you will get 1.

Now, in second to last iteration, when the cursor is at 3 and you have received 3 with i.next(). Now i.hasNext() will return true since it has 4 and you will be inside the loop, doing i.next() that consumes the whole list so next invocation of i.hasNext() will return false, terminating the loop.

Iterator hasNext用于获取最后一条记录。

答案2

得分: 1

我强烈推荐你查看一下在OpenJDK中如何实现nexthasNext方法:链接

链表迭代器有一个nextIndex变量,它指向应该在调用next时返回的项目的索引。正如你所发现的,调用next会增加这个变量的值。

假设你有一个列表[0, 1, 2, 3, 4],并且你即将第三次调用next()。在那之后,迭代器的状态如下:

            nextIndex指向这里
               |
               V
0    1    2    3    4
          ^
          |
        第三次next()的返回值

我认为你有这个困惑,是因为你不理解hasNext在做什么。hasNext不检查nextIndex之后的索引是否是有效索引。它检查的是nextIndex本身是否是有效索引。这是hasNext的实现方式:

    return nextIndex < size;

只要hasNext指向列表中的某个项目,就为真。

现在让我们来看看循环的下一次迭代会发生什么:

                 nextIndex指向这里
                    |
                    V
0    1    2    3    4
               ^
               |
             第四次next()的返回值

nextIndex4(不要与它指向的元素混淆),小于size(5),所以hasNext仍为真,循环会再次运行一次:

                      nextIndex指向这里
                         |
                         V
0    1    2    3    4
                    ^
                    |
                  第五次next()的返回值

现在nextIndex大于size,指向链表外的某个位置,所以hasNext为假,循环停止。next已经返回了所有5个元素。

英文:

I highly recommend you check out how the next and hasNext methods are implemented in the OpenJDK: Link.

The linked list iterator has an nextIndex variable that points to the index of the item that should be returned if you call next. Calling next, as you has identified, will increment this variable.

Let's say you have the list [0, 1, 2, 3, 4], and you are about to call next() for the third time. After that, the state of the iterator looks like:

            nextIndex is pointing to this
               |
               V
0    1    2    3    4
          ^
          |
        return value of the third next()

I think you have this confusion because you don't understand what hasNext is doing. hasNext does not check whether whether the index after nextIndex is a valid index. It checks whether nextIndex is a valid index. This is how hasNext is implemented:

return nextIndex &lt; size;

As long as hasNext is pointing to an item in the list, that is true.

Now let's see what happens in the next iteration of the loop:

                 nextIndex is pointing to this
                    |
                    V
0    1    2    3    4
               ^
               |
             return value of the fourth next()

nextIndex is 4 (not to be confused with the element that it points to), which is less than size (5), so hasNext is still true, so you the loop gets to run one more time:

                      nextIndex is pointing to this
                         |
                         V
0    1    2    3    4
                    ^
                    |
                  return value of the fifth next()

Now nextIndex is greater than size, pointing to something outside of the linked list, so hasNext is false, and the loop stops. next has returned all 5 elements.

答案3

得分: 1

例如,列表为1、2、3、4

请查看 java.util.LinkedList.ListItr.java

    public boolean hasNext() {
      return nextIndex < size;
    }

nextIndex = 0,size = 4,因此hasNext = true,然后如果调用next(),它会返回位置0处的项,即= 1,并增加nextIndex + 1

nextIndex = 1,size = 4,因此hasNext = true,然后如果调用next(),它会返回位置1处的项,即= 2,并增加nextIndex + 1

nextIndex = 2,size = 4,因此hasNext = true,然后如果调用next(),它会返回位置2处的项,即= 3,并增加nextIndex + 1

nextIndex = 3,size = 4,因此hasNext = true,然后如果调用next(),它会返回位置3处的项,即= 4,并增加nextIndex + 1

nextIndex = 4,size = 4,因此hasNext = FALSE

英文:

e.g., list as 1, 2, 3, 4

See the java.util.LinkedList.ListItr.java

public boolean hasNext() {
  return nextIndex &lt; size;
}

nextIndex = 0, size = 4, hence hasNext = true, then if you you call next() then it returns item from position 0 that is = 1 and increment nextIndex + 1

nextIndex = 1, size = 4, hence hasNext = true, then if you you call next() then it returns item from position 1 that is = 2 and increment nextIndex + 1

nextIndex = 2, size = 4, hence hasNext = true, then if you you call next() then it returns item from position 2 that is = 3 and increment nextIndex + 1

nextIndex = 3, size = 4, hence hasNext = true, then if you you call next() then it returns item from position 3 that is = 4 and increment nextIndex + 1

nextIndex = 4, size = 4, hence hasNext = FALSE

答案4

得分: 1

Iterator是一个接口。下面是hasNext()next()方法如何工作的代码示例。

// Java代码示例演示了如何使用迭代器
import java.io.*;
import java.util.*;

class Test {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();

        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");

        // 迭代器遍历列表
        Iterator<String> iterator = list.iterator();

        System.out.println("列表元素: ");

        while (iterator.hasNext()) {
            System.out.print(iterator.hasNext() + " " + iterator.next() + " " + iterator.hasNext() + "\n");
        }
        System.out.println();
    }
}

以上代码的输出:
列表元素:
true A true
true B true
true C true
true D true
true E false

hasNext()next()方法的定义:

public class NextFromIterator implements Iterator<String> {
    private int position = -1;
    private List<String> list = new ArrayList<String>() {{
        add("alpha"); add("bravo"); add("charlie"); add("delta"); add("echo"); add("foxtrot");
    }};

    public boolean hasNext() {
        return next() != null;  // 错误:调用了'next'
    }

    public String next() {
        position++;
        return position < list.size() ? list.get(position) : null;
    }

    public void remove() {
        // ...
    }

    public static void main(String[] args) {
        NextFromIterator x = new NextFromIterator();
        while (x.hasNext()) {
            System.out.println(x.next());
        }
    }
}

每次迭代next()方法将其指针增加1,初始时指针指向-1。然后将指针与迭代器的实际大小进行比较,如果小于实际大小,则此方法返回该元素,否则返回null。在hasNext()方法中,每次循环都调用了next()方法,并在此处检查是否等于null。

英文:

Iterator is a Interface. Here is code how hasNext() and next() method works.

// Java code to illustrate the use of iterator 
import java.io.*; 
import java.util.*; 

class Test { 
	public static void main(String[] args) 
	{ 
		ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;(); 

		list.add(&quot;A&quot;); 
		list.add(&quot;B&quot;); 
		list.add(&quot;C&quot;); 
		list.add(&quot;D&quot;); 
		list.add(&quot;E&quot;); 

		// Iterator to traverse the list 
		Iterator iterator = list.iterator(); 

		System.out.println(&quot;List elements : &quot;); 

		while (iterator.hasNext()) 
        {
          
		  System.out.print(iterator.hasNext()+&quot; &quot;+iterator.next() + &quot; &quot;+iterator.hasNext()+&quot;\n&quot;); 
        }
		System.out.println(); 
	} 
} 

output of above code:
List elements :
true A true
true B true
true C true
true D true
true E false

Defination of hasNext() and next() methods:

public class NextFromIterator implements Iterator&lt;String&gt; {
    private int position = -1;
    private List&lt;String&gt; list = new ArrayList&lt;String&gt;() {{
        add(&quot;alpha&quot;); add(&quot;bravo&quot;); add(&quot;charlie&quot;); add(&quot;delta&quot;); add(&quot;echo&quot;); add(&quot;foxtrot&quot;);
    }};
     
    public boolean hasNext() {
        return next() != null;  // BAD: Call to &#39;next&#39;
    }
     
    public String next() {
        position++;
        return position &lt; list.size() ? list.get(position) : null;
    }
 
    public void remove() {
        // ...
    }
     
    public static void main(String[] args) {
        NextFromIterator x = new NextFromIterator();
        while(x.hasNext()) {
            System.out.println(x.next());
        }
    }

Every Iteration next() increment the its pointer by 1 initial it is point to -1. After that pointer is checked with actual size of iterator if it is less than that then this method returns that element otherwise it returns null. In hasNext() method this next() method called for every loop and here it is checked that weather it is equal to null or not.

huangapple
  • 本文由 发表于 2020年9月30日 11:44:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/64130533.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定