Java 程序使用 ListIterator 获取上一个和下一个索引
若要精确计算上一个和下一个索引,你需要使用 Iterator 的 next() 方法。这最终将帮助你进一步了解迭代器。我们先创建一个 ArrayList ,再添加一些元素——
ArrayList <Integer> arrList = new ArrayList <Integer> (); arrList.add(100); arrList.add(200); arrList.add(300); arrList.add(400); arrList.add(500); arrList.add(600); arrList.add(700); arrList.add(800); arrList.add(900); arrList.add(1000);
然后,创建一个 ListIterator——
ListIterator<Integer>iterator = arrList.listIterator();
现在获取上一个和下一个索引——
iterator.previousIndex(); iterator.nextIndex();
示例
import java.util.ArrayList; import java.util.ListIterator; public class Demo { public static void main(String[] args) { ArrayList<Integer>arrList = new ArrayList<Integer>(); arrList.add(100); arrList.add(200); arrList.add(300); arrList.add(400); arrList.add(500); arrList.add(600); arrList.add(700); arrList.add(800); arrList.add(900); arrList.add(1000); System.out.println("ArrayList..."); for (Integer i: arrList) System.out.println(i); ListIterator<Integer>iterator = arrList.listIterator(); System.out.println("Previous Index =" + iterator.previousIndex()); System.out.println("Next Index = " + iterator.nextIndex()); iterator.next(); System.out.println("Previous Index = " + iterator.previousIndex()); System.out.println("Next Index =" + iterator.nextIndex()); iterator.next(); iterator.next(); System.out.println("Previous Index = " + iterator.previousIndex()); System.out.println("Next Index = " + iterator.nextIndex()); } }
输出
ArrayList... 100 200 300 400 500 600 700 800 900 1000 Previous Index =-1 Next Index = 0 Previous Index = 0 Next Index =1 Previous Index = 2 Next Index = 3
广告