import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListTest {
/*
* 功能:用集合遍历学生类的数据
* */
public static void main(String[] args) {
ArrayList<Student> stringArrayList = new ArrayList<Student>();
Student student1 = new Student("孙悟空", 99);
Student student2 = new Student("猪八戒", 88);
Student student3 = new Student("嫦娥", 7);
//把学生的数据赋值到集合
stringArrayList.add(student1);
stringArrayList.add(student2);
stringArrayList.add(student3);
//输出集合,先输出看看
System.out.println(stringArrayList);
//用集合遍历,
// 方法1用迭代器,
Iterator<Student> iterator = stringArrayList.iterator();
while (iterator.hasNext()) {
Student next = iterator.next();
//直接输出迭代器的对象,是有类名,{}属性,数据
System.out.println(next);
//只获取类的数据用,类名 点 getXXX
String name = next.getName();
Integer age = next.getAge();
System.out.println(name + " " + age);
}
// 方法2用for
for (int i = 0; i < stringArrayList.size(); i++) {
//获取集合的数据,用集合对象点 get
//这是获得集合的每一个对象。有类名{}
Student student = stringArrayList.get(i);
System.out.println("方法2 for " + student);
//只获取类的数据用,实体类名 点 getXXX
String name = student.getName();
Integer age = student.getAge();
System.out.println(name + " " + age);
}
}
}