Java中List集合存储对象的几种遍历方式
List集合存储对象的遍历方式主要有以下三种(可根据自己实际需要选取遍历方式): (1)使用迭代器遍历,集合特有的遍历方式 (2)使用普通for循环遍历,带有索引 (3)使用增强for循环,最方便的方式
程序代码如下: 1、先定义一个学生类Student
public class Student { private String name; private String dept; private String age; public Student() { } public Student(String name, String dept, String age) { this.name = name; this.dept = dept; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }
2、创建集合对象,开始遍历
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ListDemo { public static void main(String[] args) { List<Student> list=new ArrayList<Student>(); //创建集合对象 Student s1 = new Student("Cheng", "IMIS", "22"); Student s2 = new Student("小学生", "CS", "20"); Student s3 = new Student("King", "IMIS", "23"); //将Student对象添加到集合中 list.add(s1); list.add(s2); list.add(s3); //使用迭代器遍历,集合特有的遍历方式 Iterator<Student> it = list.iterator(); while (it.hasNext()){ Student s=it.next(); System.out.println(s.getName()+","+s.getDept()+","+s.getAge()); } System.out.println("--------"); //使用普通for循环遍历,带有索引 for (int i=0;i<list.size();i++){ Student s=list.get(i); System.out.println(s.getName()+","+s.getDept()+","+s.getAge()); } System.out.println("--------"); //使用增强for循环,最方便的方式 for (Student s:list){ System.out.println(s.getName()+","+s.getDept()+","+s.getAge()); } } }
输出结果如下:
Cheng,IMIS,22 小学生,CS,20 King,IMIS,23 -------- Cheng,IMIS,22 小学生,CS,20 King,IMIS,23 -------- Cheng,IMIS,22 小学生,CS,20 King,IMIS,23