gpt4 book ai didi

java - 为什么listiterator中的hasPrevious()和add()组合会进入无限循环,而hasNext()和add()则不会?

转载 作者:行者123 更新时间:2023-12-02 08:51:06 25 4
gpt4 key购买 nike

具有两个元素的ArrayList

     ArrayList<String> a = new ArrayList<String>() { 
{
add("hai");
add("hello");
}
};

为该列表创建了一个列表迭代器

   ListIterator l = a.listIterator();

使用 next 遍历并向列表添加元素“bye”

   while (l.hasNext()) {              

l.next();
l.add("bye");

}
System.out.println(a);

以上代码的输出为= [hai,bye,hello,bye]

遍历到列表的最后一个

    while(l.hasNext()) {             
l.next();
}

使用 prev 向前遍历并将元素“bye”添加到列表

    while (l.hasPrevious()) {         

l.previous();
l.add("bye");

}
System.out.println(a);

无限且不打印任何内容!!!

最佳答案

嗯,ListIteratoradd 的 Javadoc 解释说:

Inserts the specified element into the list (optional operation). The element is inserted immediately before the element that would be returned by next, if any, and after the element that would be returned by previous, if any. (If the list contains no elements, the new element becomes the sole element on the list.) The new element is inserted before the implicit cursor: a subsequent call to next would be unaffected, and a subsequent call to previous would return the new element.

l.previous 返回您刚刚通过 l.add("bye") 添加的元素,因此您永远不会到达 的开头列表。因此无限循环。

如果列表如下所示:

hai       hello
^
|
cursor

调用l.previous();返回“hello”并将光标向后移动:

hai            hello
^
|
cursor

调用 l.add("bye"); 在“hai”和“hello”之间以及光标之前添加新元素:

hai      bye      hello
^
|
cursor

因此下一次调用l.previous()将返回“bye”。

因此你的循环永远不会到达List的开头。

关于java - 为什么listiterator中的hasPrevious()和add()组合会进入无限循环,而hasNext()和add()则不会?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59711892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com