Collection集合

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());

              }

 

       }

 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值