Java如何使用ListIterator迭代LinkedList元素?
本示例向您展示如何使用ListIterator接口来迭代LinkedList的元素。
package org.nhooo.example.util; import java.util.List; import java.util.LinkedList; import java.util.ListIterator; public class LinkedListListIterator { public static void main(String[] args) { List<String> grades = new LinkedList<>(); grades.add("A"); grades.add("B"); grades.add("C"); grades.add("D"); grades.add("E"); // 使用ListIterator从LinkedList检索对象 // 接口。 ListIterator li = grades.listIterator(); while (li.hasNext()) { System.out.println("Grades: " + li.next()); System.out.println(" hasPrevious : " + li.hasPrevious()); System.out.println(" hasNext : " + li.hasNext()); System.out.println(" previousIndex: " + li.previousIndex()); System.out.println(" nextIndex : " + li.nextIndex()); } } }
该程序将打印以下输出:
Grades: A hasPrevious : true hasNext : true previousIndex: 0 nextIndex : 1 Grades: B hasPrevious : true hasNext : true previousIndex: 1 nextIndex : 2 Grades: C hasPrevious : true hasNext : true previousIndex: 2 nextIndex : 3 Grades: D hasPrevious : true hasNext : true previousIndex: 3 nextIndex : 4 Grades: E hasPrevious : true hasNext : false previousIndex: 4 nextIndex : 5