Java程序使用ListIterator获取上一个和下一个索引
要获得上一个和下一个索引的准确评估,您需要使用next()
Iterator的方法。这最终将帮助您获得对Iterators的更多了解。让我们首先创建一个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