创建一个ArrayList集合对象,并为这个集合添加学生集合元素,同时迭代器获取集合中的对象。其中,学生类属性包括姓名和年龄。
package cn.itcast2;
public class Student {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
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;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
package cn.itcast2;
import java.util.ArrayList;
import java.util.Iterator;
public class Test3 {
public static void main(String[] args) {
ArrayList<Student> stu = new ArrayList<Student>();
stu.add(new Student("小明",20));
stu.add(new Student("小倩",25));
stu.add(new Student("小芳",30));
//调用iterator()方法,返回Iterable对象
Iterator<Student> iterator = stu.iterator();
while(iterator.hasNext()){
Student ss = iterator.next();
System.out.println(ss);
}
}
}
|
|