Java ArrayList几种遍历方法

import java.util.ArrayList;
import java.util.Iterator;

public class StringSampleDemo {
    public static void main(String[] args) {
        ArrayList al = new ArrayList();
        al.add("1");
        al.add("2");
        al.add("3");
        al.add("4");

        // 方式1
        for (Object o : al) {
            System.out.println(o);
        }

        System.out.println("----------------------------");

        // 方式2
        Iterator it = al.iterator(); //迭代器
        while (it.hasNext()) {
            System.out.println(it.next());
        }

        System.out.println("----------------------------");
        // 方式3
        for (int i = 0; i < al.size(); i++) {
            System.out.println(al.get(i));
        }

        System.out.println("----------------------------");
        // 方式4
        al.forEach(x -> System.out.println(x));
    }
}

  

posted @ 2019-09-30 13:34  深南大道  阅读(987)  评论(0编辑  收藏  举报