package it.cast;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionTterator {
public static void main(String[] args) {
//创建集合对象
Collection collection = new ArrayList();
//创建学生对象
TestStudet testStudet1 = new TestStudet("张三", 23);
TestStudet testStudet2 = new TestStudet("李四", 24);
TestStudet testStudet3 = new TestStudet("王五", 25);
TestStudet testStudet4 = new TestStudet("赵六", 26);
//把学生对象放入集合当中
collection.add(testStudet1);
collection.add(testStudet2);
collection.add(testStudet3);
collection.add(testStudet4);
//遍历集合对象
//以前是创建对象数组,然后遍历数字得到结果
//现在利用Iterator遍历,格式如下
Iterator iterator = collection.iterator();
//判断有没有 元素
while (iterator.hasNext()) {
//不要多次使用next方法,那样会使输出返回异常
TestStudet testStudet =(TestStudet)iterator.next();
System.out.println(testStudet.getNameString()+"---"+testStudet.getAge());
}
}
}
|
|