228 (案例)List集合存储学生对象并遍历
> 225做过这个案例,当时用的是Collection集合
【需求】
创建一个存储学生对象的集合,存储3个学生对象,遍历这个集合。
【思路】
1.定义学生类
2.创建Collection集合对象
3.创建学生对象
4.添加学生到集合中
5.遍历集合。2种方法:1.iterator迭代器,2.for循环
--------------------------------------------------------------
class Student228
略
--------------------------------------------------------------
package e226aso;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ListDemo228 {
public static void main(String[] args) {
List<Student228> list = new ArrayList<Student228>();
Student228 s1 = new Student228("Tracy", 228);
Student228 s2 = new Student228("Ben", 70);
Student228 s3 = new Student228("Mulan", 22);
list.add(s1);
list.add(s2);
list.add(s3);
// 使用迭代器遍历
Iterator<Student228> it = list.iterator();
// Student228 s = it.next();报错NoSuchElementException
while(it.hasNext()){
Student228 s = it.next();
System.out.println(s.getName() + "," + s.getAge());
}
//ctrl alt l格式化
// 使用for-loop遍历
System.out.println("---");
for(int i=0;i<list.size();i++){
Student228 ss = list.get(i);
System.out.println(ss.getName()+","+ss.getAge());
}
}
}
--------------------------------------------------------------
Tracy,228
Ben,70
Mulan,22
---
Tracy,228
Ben,70
Mulan,22