List集合存放有顺序,可重复的数据
代码实例
首先定义Student类
public class Student {
private int age;//年龄
private String name;//姓名
private int score;//成绩
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
//构造函数
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int age, String name,int score) {
super();
this.age = age;
this.name = name;
this.score = score;
}
//重写toString方法
@Override
public String toString() {
return "Student [age=" + age + ", name=" + name + ",score=" + score+"]";
}
}
然后测试Student类
import java.util.ArrayList;
import java.util.List;
public class TestStudent {
public static void main(String[] args) {
//创建集合对象,实现类ArrayList
List<Student> list = new ArrayList<Student>();
//创建学生对象
Student stu1 = new Student(13,"Sary",98);
Student stu2 = new Student(14,"Mack",89);
Student stu3 = new Student(15,"Alsa",92);
//将对象添加到集合中
list.add(stu1);
list.add(stu2);
list.add(stu3);
//遍历集合语法 for(具体的数据类型 别名:集合)
for (Student stu : list) {
System.out.println(stu);
}
}
}