/*List集合存储学生对象的三种遍历方式
创建一个存储学生对象的集合,存储三个学生对象,使用程序实现控制台遍历该集合
- 定义一个学生类
- 创建List集合对象
- 创建学生对象
- .把学生对象添加到集合
- 遍历集合
迭代器:集合特有的遍历方式
普通for:带有索引的遍历方式
增强for:最方便的遍历方式
*/
定义一个学生类
使用Alt+Insert可自动生成
package Case_07;
public class Student {
private String name;
private int age;
public Student(){}
public Student(String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
关于遍历方式的总结:
一般情况下,只用这两种就可以了
- 如果只是为了遍历,就用增强for,,因为最方便
- 如果在操作的过程中用到索引,只能选择普通for,因为普通for是带有索引的遍历方式
package Case_07;
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 s = new Student("魏无羡",16);
Student s1 = new Student("蓝忘机",18);
Student s2 =new Student("魏婴",16);
list.add(s);
list.add(s1);
list.add(s2);
// 迭代器:集合特有的遍历方式
Iterator<Student> it = list.iterator();
while (it.hasNext()){
Student st = it.next();
System.out.println(st.getName()+","+st.getAge());
}
System.out.println("***************");
// 普通for:带有索引的遍历方式
for (int i = 0;i<list.size();i++){
Student st = list.get(i);
System.out.println(st.getName()+","+st.getAge());
}
System.out.println("***************");
// 增强for:最方便的遍历方式
for (Student st:list){
System.out.println(st.getName()+","+st.getAge());
}
}
}