List集合存储学生对象及三种方式遍历
package com.itheima_80;
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;
}
}
package com.itheima_80;
/*
需求:创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合
思路:
1.定义学生类
2.创建list集合
3.创建学生对象
4.把学生添加到该集合
5.遍历集合
5.1迭代器:集合特有的遍历方式
5.2普通for:带有索引的遍历方式
5.3增强for:最方面的遍历方式
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
//创建list集合
List<Student> list = new ArrayList<Student>();
//创建学生对象
Student s1 = new Student("王昱翔",35);
Student s2 = new Student("王新权",30);
Student s3 = new Student("王顺顺",38);
//把学生添加到该集合
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());
}
}
}