集合练习
定义一个集合,添加一些学生对象,并进行遍历 学生类:
package Student;
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 getzName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
测试类:
package Student;
import java.util.ArrayList;
public class TestStudent {
public static void main(String[] args) {
// 创建集合
ArrayList<Student> kon = new ArrayList<>();
// 添加对象
Student s1 = new Student("张三", 18);
Student s2 = new Student("李四", 17);
Student s3 = new Student("王五", 16);
// 添加元素
kon.add(s1);
kon.add(s2);
kon.add(s3);
// 遍历
for (int i = 0; i < kon.size(); i++) {
Student stu = kon.get(i);
System.out.println(stu.getzName() + stu.getAge());
}
}
}