问题描述
我希望能够使用 ListIterator
将元素插入到 ArrayList<String>
,但不知何故,即使在阅读了与 add 方法相关的文档后,我还是感到困惑ListIterator
类,如果我做这样的事情
I want to be able to insert elements to the ArrayList<String>
using ListIterator
, but somehow I am confused even after reading the documentation related to the add method of the ListIterator
class, if I do something like this
for(int i = 0 ; i < list.size() ; ++i)
listIterator.add( list.get(i) );
这段代码片段对我的列表迭代器做了什么,它将列表迭代器移动到哪里?
What does this code snippet do to my list iterator, where does it move the list iterator?
当我运行以下代码时,我得到的结果是Hi"-:
When I run the following code I get the result as "Hi" -:
import java.util.ArrayList;
import java.util.ListIterator;
public class ListIter {
public static void main(String[] args) {
String[] s = {"Hi", "I", "am", "Ankit"};
ArrayList<String> list = new ArrayList<>();
ListIterator<String> listIterator = list.listIterator();
for (int i = 0; i < s.length; ++i) {
listIterator.add(s[i]);
}
while (listIterator.hasPrevious()) {
listIterator.previous();
}
System.out.println(listIterator.next());
}
}
请问这个输出是怎么产生的?
Kindly tell how is this output being generated?
推荐答案
你没有正确使用迭代器.使用迭代器的正确方法是使用迭代器本身而不是索引来遍历列表.
You are not using iterator properly. The correct way using iterators is traverse the list with the iterator itself rather than by index.
ListIterator<SomeObject> listIterator = list.listIterator();
while(listIterator.hasNext()){
SomeObject o = listIterator.next();
listIterator.add(new SomeObject());
}
阅读 ListIterator#添加()
一个简单的例子:
public static void main(String args []){
List<String> list= new ArrayList<String>();
list.add("hi");
list.add("whats up");
list.add("how are you");
list.add("bye");
ListIterator<String> iterator = list.listIterator();
int i=0;
while(iterator.hasNext()){
iterator.next();
iterator.add(Integer.toString(i++));
}
System.out.println(list);
//output: [hi, 0, whats up, 1, how are you, 2, bye, 3]
}
}
这篇关于List Iterator 的 add() 方法对迭代器做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!