我必须以这种方式迭代数组列表。
ArrayList<Integer> li = new ArrayList<Integer>();
li.add(20);
li.add(30);
li.add(40);
li.add(50);
li.add(70);
for (int i = 0; i < li.size() - 1; i++)
System.out.println(li.get(i) + " " + li.get(i + 1));
输出:
20 30
30 40
40 50
50 70
如何使用迭代器执行相同的操作?
最佳答案
使用两个迭代器。我对此进行了测试,它对我有用。
Iterator<Integer> first = li.listIterator();
// Will raise IndexOutOfBoundsException if list is empty.
Iterator<Integer> second = li.listIterator(1);
while (second.hasNext()) {
System.out.println(first.next() + " " + second.next());
}
编辑:不需要内部if
。愚蠢的我。
说明:listIterator(index)
方法返回一个从列表中指定位置开始的迭代器,而 listIterator()
返回一个从位置 0 开始的迭代器。
因此,first
迭代器从 0
开始,second
从 1
开始。那么这只是在两者上打印 next()
的问题。无论列表中的元素数量是奇数还是偶数,这都将起作用。
编辑2
今天我的逻辑能力很弱。谢谢@barjak指出有关空列表和不必要的 first.hasNext()
的情况。
关于java - 在这种情况下如何使用迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3784519/