Java中List集合的三种遍历方式

假设变量 list 是需要循环遍历的变量

第一种、最基础的遍历方式:for循环,指定下标长度

for (int i = 0; i < list.size(); i++) {
     News s = (News)list.get(i);
     System.out.println(s.getId()+"  "+s.getTitle()+"  "+s.getAuthor());
}

第二种、较为简洁的遍历方式:使用foreach遍历List

for (News s : list) {
     System.out.println(s.getId()+"  "+s.getTitle()+"  "+s.getAuthor());
}

第三种、适用迭代器Iterator遍历:直接根据List集合的自动遍历

while (iter.hasNext()) {
            News s = (News) iter.next();
            System.out.println(s.getId()+"  "+s.getTitle()+"  "+s.getAuthor());
}

猜你喜欢

转载自www.cnblogs.com/kevinlucky/p/12592788.html