Java 类和List集合 迭代器遍历练习题
1. 创建班级类(Classes),具有两个属性:班级人数,班级名称;创建学生类(Student),具有三个属性:学生姓名,学号,所在班级(Classes类型对象),所有属性都通过构造方法赋值,并具有相应存取器方法。在测试类中,创建存储Student类型的List,并向其添加十个学生的信息,通过迭代器,迭代该List,并将学生所在班级名称打印到控制台。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
//定义一个班级类
class Classes{
private int count;
private String name;
//构造方法
public Classes(int count, String name) {
super();
this.count = count;
this.name = name;
}
//getter/setter方法
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//定义一个学生类
class Student {
private String name;
private String id;
private Classes classes;
public Student(String name, String id, Classes classes) {
this.name = name;
this.id = id;
this.classes = classes;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Classes getClasses() {
return classes;
}
public void setClasses(Classes classes) {
this.classes = classes;
}
}
public class Test1_06 {
public static void main(String[] args) {
List list = new ArrayList ();
Classes cla = new Classes(10, "java0421"); //生成班级
for (int i = 0; i < 10; i++) { //循环10遍
Student s = new Student(""+i, i+"", cla); //生成学生
list.add(s); //添加学生
}
//通过迭代器,迭代该list集合
for(ListIterator it = list.listIterator();it.hasNext();) {
Object obj = it.next();
if (obj instanceof Student) {
Student s = (Student) obj;
System.out.println(s.getClasses().getName());
}
}
}
}