List的遍历

发布时间 2023-11-09 21:25:51作者: kandhera

List的遍历方式

迭代器遍历,普通for遍历,增强for遍历,Lamda遍历,列表迭代器遍历

演示代码如下

public class Main {
    public static void main(String a[]) {
        List<String> list  = new ArrayList<>();
        list.add("zhang");
        list.add("wang");
        list.add("li");
        list.add("chen");
        list.add("lin");
        
        //1.迭代器遍历,需要用到Iterator
        System.out.println("迭代器遍历");
        Iterator<String> it = list.iterator();
        while (it.hasNext()) {
            System.out.printf(it.next()+"  ");
        }
        System.out.println();
        
          //2. 普通for遍历,借用size()方法
        System.out.println("普通for遍历");
        for (int i = 0; i < list.size(); i++) {
            System.out.printf(list.get(i)+"  ");
        }
        System.out.println();
        
        //3.增强for,也就是foreach
        System.out.println("增强for遍历");
        for (String string : list) {
            System.out.printf(string+"  ");
        }
        System.out.println();
        
        //4.lamda遍历,利用List的forEach
        System.out.println("Lamda遍历");
        list.forEach(s->System.out.printf(s+"  "));
        System.out.println();
        
        //5.列表迭代器
        System.out.println("列表迭代器遍历");
        ListIterator<String> lit = list.listIterator();
        while(lit.hasNext()) {
            System.out.printf(lit.next()+"  ");
        }
    }
}

运行截图:

 总结:

迭代器遍历:这种方法可以保证遍历的顺序,但每次迭代都会创建新的Iterator对象,这会影响性能。此外,使用Iterator时需要注意检查hasNext(),这可能会使代码显得不够简洁,甚至报错。

 

普通for遍历:这种方法需要知道元素的索引,这在某些情况下可能是必要的。然而,如果List很大,那么每次访问都需要进行索引计算,这会降低性能。此外,这种方法也无法保证遍历的顺序。

增强for遍历:这种方法最简单,可读性最好,但它的性能不是最优。因为每次迭代都会创建Iterator对象,而创建Iterator对象是有额外开销的。此外,这种方法不能保证遍历的顺序,因为List的元素可能被其他线程改变。

Lamda遍历这种方法在Java 8之后引入,结合了for-each循环和索引,使遍历更高效。它没有创建额外的Iterator或ListIterator对象,因此性能较好。此外,使用这种方法时不需要检查遍历是否结束,因为它会在遍历结束后自动停止。

 

列表迭代器遍历:这种方法可以保证遍历的顺序,并且可以获取前一个和后一个元素。但是,它也有类似Iterator的问题,即每次迭代需要创建新的ListIterator对象。不过它可以在遍历时添加元素,这是迭代器不能实现的