一:ArrayList的遍历
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* ArrayList的遍历
*/
public class Test {
public static void main(String[] args) {
List<Integer> 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<Integer> 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<Integer> 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<Integer> it1= list.listIterator();
while(it1.hasNext()){
System.out.print(it1.next()+" ");
}
System.out.println();
//4.使用反向迭代器遍历——反向遍历
ListIterator<Integer> it2= list.listIterator(list.size());
while(it1.hasPrevious()){
System.out.print(it1.previous()+" ");
}
System.out.println();
}
}