代码语言:javascript复制
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(10);
arrayList.add(20);
arrayList.add(30);
//第一种遍历方式
System.out.println(arrayList);//[10, 20, 30]
//第二种遍历方式 for
for (int i = 0; i < arrayList.size(); i ) {
System.out.print(arrayList.get(i) " ");//10 20 30
}
System.out.println();
//第三种遍历方式 for-each
for (int x:arrayList) {
System.out.print(x " ");//10 20 30
}
System.out.println();
//第四种遍历方式 迭代器·
Iterator<Integer> it = arrayList.iterator();
while(it.hasNext()) {
System.out.print(it.next() " ");//10 20 30
}
System.out.println();
//第五种遍历方式
ListIterator<Integer> it1 = arrayList.listIterator();
while(it1.hasNext()) {
System.out.print(it1.next() " ");//10 20 30
}
System.out.println();
//6.从后往前遍历
ListIterator<Integer> it2 = arrayList.listIterator(arrayList.size());
while(it1.hasPrevious()) {
System.out.print(it1.previous() " ");//30 20 10
}
System.out.println();
}