java集合的三种遍历

public class HomeWork {

public static void main(String[] args) {
    //定义链表集合
    List<Student1> list = new ArrayList<Student1>();
    Student1 s1= new Student1("杜",18);
    Student1 s2= new Student1("刘",19);
    Student1 s3= new Student1("张",20);

    list.add(s1);
    list.add(s2);
    list.add(s3);
    //第一种:数组遍历
    Object[] arr = list.toArray();   //将集合转化为数组
    for(Object i:arr) {               //遍历数组
        Student1 next =(Student1)i;
                  System.out.println(next.getName()+"---"+next.getAge());
    }
    //第二种遍历:迭代器遍历(Iterator)
    Iterator<Student1> it2 = list.iterator();  //定义迭代器
    while(it2.hasNext()) {
        Student1 s = it2.next();
        System.out.println(s.getName()+"--"+s.getAge());
    }
    //第三种:特有遍历(List的特有遍历)  
    for(int i=0;i<list.size();i++) {
        System.out.println(list.get(i).getName()+"-----"+list.get(i).getAge());
    }
    for(Student1 stu:list) {
        System.out.println(stu.getName()+"--"+stu.getAge());
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值