遍历一个List有哪些不同的方式?

AbrahamW

关注

阅读 61

2022-02-23

List < String > strList = new ArrayList <> ();

// 使用 for-each 循环

for ( String obj : strList ){

System . out . println ( obj );

}

//using iterator

Iterator < String > it = strList . iterator ();

while ( it . hasNext ()){

String obj = it . next ();

System . out . println ( obj );

}

使用迭代器更加线程安全,因为它可以确保,在当前遍历的集合元素被更改的时候,它会抛出

ConcurrentModificationException

精彩评论(0)

0 0 举报