一:ArrayList的遍历
import java.util.ArrayList;import java.util.Iterator;import java.util.List;/** * ArrayList的遍历 */public class Test {public static void main(String[] args) {List list = new ArrayList();list.add(5);list.add(6);list.add(7);list.add(8);list.add(9);//1.直接输出System.out.print(list);System.out.println();//2.for循环for (int i = 0; i < list.size(); i++) {System.out.print(list.get(i) + " ");}System.out.println();//3.foreach遍历for (int x : list) {System.out.print(x + " ");}System.out.println();//4.使用迭代器遍历Iterator it1 = list.listIterator();while (it1.hasNext()) {System.out.print(it1.next() + " ");}System.out.println();}}
二:LinkedList的遍历
import java.util.LinkedList;import java.util.ListIterator;public class Test {public static void main(String[] args) {LinkedList list=new LinkedList();list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);//1.直接输出:因为重写了toString()System.out.print(list);System.out.println();//2.foreach遍历for (int x:list) {System.out.print(x+" ");}System.out.println();//3.使用迭代器遍历——正向遍历ListIterator it1= list.listIterator();while(it1.hasNext()){System.out.print(it1.next()+" ");}System.out.println();//4.使用反向迭代器遍历——反向遍历ListIterator it2= list.listIterator(list.size());while(it1.hasPrevious()){System.out.print(it1.previous()+" ");}System.out.println();}}