Collection
packagecom.newedu.jb.day17.collection;
importjava.util.ArrayList;
importjava.util.Collection;
importjava.util.Iterator;
public classCollecitonDemo {
public static void main(String[] args) {
// 第一步:创建集合对象
// ctrl+shift +o:自动导包
Collection col = new ArrayList();
// 第二步:创建集合元素
String str1 = "jerry";
String str2 = "susan";
String str3 = "peter";
// 第三步:向集合中添加集合元素
col.add(str1);
col.add(str2);
col.add(str3);
// 第四步:遍历集合 (左边接口 = 右边实现了该接口子类对象)
Iterator iter = col.iterator();
//System.out.println(iter.next());
//System.out.println(iter.next());
//System.out.println(iter.next());
// NoSuchElementException
// System.out.println(iter.next());
System.out.println("===============");
Collection col1 = new ArrayList();
Student stu1 = newStudent("jerry", 20);
Student stu2 = newStudent("susan", 19);
Student stu3 = newStudent("peter", 21);
col1.add(stu1);
col1.add(stu2);
col1.add(stu3);
Iterator iter1 = col1.iterator();
while (iter1.hasNext()) {
// 单独输出对象的成员变量呢?
//System.out.println(iter1.next());
// Object obj =iter1.next();
// 向集合中存储的时候,存Student对象,取Object对象
// 多态的时候,通过父类的引用无法查看子类的特有成员
// 如果想查看子类的特有成员,就必须向下类型转换
// Student stu =(Student)obj;
//System.out.println(stu.getName() +"=="+stu.getAge());
System.out.println(((Student)iter1.next()).getName()
+"===" + ((Student) iter1.next()).getAge());
}
}
}