package package5;
import package4.Student;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
//List集合存储学生对象用三种方式遍历
public class Test {
public static void main(String[] args) {
//创建集合对象
List<Student> list =new ArrayList<>();
//创建学生对象
package4.Student s1 =new package4.Student("张三",21);
package4.Student s2 =new package4.Student("李四",22);
package4.Student s3 =new Student("王五",23);
//添加到集合中
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.getAge());
}
System.out.println("--------------");
//普通for:带有索引的遍历方式
for (int i = 0; i < list.size(); i++) {
Student s = list.get(i);
System.out.println(s.getName()+", "+s.getAge());
}
System.out.println("--------------");
//增强for:最方便的遍历方式
for(Student s:list){
System.out.println(s.getName()+", "+s.getAge());
}
}
}
标签:存储,遍历,List,list,System,Student,package4,out
From: https://www.cnblogs.com/knlf/p/16794374.html