集合的三种遍历方法

 1 package CollectionTest;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Iterator;
 5 
 6 public class ArrayListTest02 {
 7     public static void main(String[] args) {
 8         ArrayList<Student> students = new ArrayList<>();
 9         students.add(new Student("小王",23,25600));
10         students.add(new Student("小张",25,35600));
11         students.add(new Student("小侬",24,46600));
12         students.add(new Student("小李",26,45600));
13         //方法一:使用传统的遍历方式for循环
14         System.out.println("============使用传统的for循环进行遍历==================");
15         for (int i = 0; i <students.size() ; i++) {
16             Student student = students.get(i);
17             System.out.println("姓名:"+student.getName()+","+"年龄:"+student.getAge()+","+"工资:"+student.getSal());
18         }
19         System.out.println("============使用增强for循环进行遍历==================");
20         //方法二:使用增强for循环
21         for (Student student :students) {
22             System.out.println("姓名:"+student.getName()+"年龄:"+student.getAge()+"工资:"+student.getSal());
23         }
24         System.out.println("============使用迭代器iterator进行遍历==================");
25         //1.先获取迭代器
26         Iterator<Student> iterator = students.iterator();
27         //2.再使用while循环进行遍历
28         while (iterator.hasNext()) {
29             Student student =  iterator.next();
30             System.out.println("姓名;"+student.getName()+"\t"+"年龄;"+student.getAge()+"岁"+"\t"+"工资;"+student.getSal());
31             
32         }
33     }
34 }

 

posted @ 2022-08-07 17:10  捞月亮的渔夫  阅读(162)  评论(0)    收藏  举报