使用Java中的ListIterator遍历ArrayList
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
热门推荐
10 病人祝福语老师寄语简短
11 新娘生孩子祝福语简短
12 婆婆66岁祝福语简短
13 今天孩子高考祝福语简短
14 送彩票生日祝福语简短
15 分别祝福语简短情话英文
16 画室揭牌仪式祝福语简短
17 女友妈妈生日祝福语简短
18 离别赠言离职祝福语简短