ListIterator可用于在ArrayList的正向和反向遍历元素。
如果在ArrayList中有更多的元素同时正向遍历,则ListIterator中的hasNext()方法返回true,否则返回false。next()方法返回ArrayList中的下一个元素并前进光标位置。
如果在ArrayList中有更多元素同时沿相反方向遍历,则ListIterator中的hasPrevious()方法返回true,否则返回false。方法previous()返回ArrayList中的前一个元素,并向后减小光标位置。
演示该程序的程序如下。
import java.util.ArrayList;
import java.util.ListIterator;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String> aList = new ArrayList<String>();
      aList.add("Apple");
      aList.add("Mango");
      aList.add("Guava");
      aList.add("Orange");
      aList.add("Peach");
      ListIterator i = aList.listIterator();
      System.out.println("The ArrayList elements in the forward direction are: ");
      while (i.hasNext()) {
         System.out.println(i.next());
      }
      System.out.println("\nThe ArrayList elements in the reverse direction are: ");
      while (i.hasPrevious()) {
         System.out.println(i.previous());
      }
   }
}输出结果
上面程序的输出如下
向前的ArrayList元素是
Apple Mango Guava Orange Peach The ArrayList elements in the reverse direction are: Peach Orange Guava Mango Apple