Java学习笔记116——集合的遍历

集合的遍历

集合的遍历:目的就是将集合中的元素依次取出来 Object[] toArray()

需求1、 把集合转成数组,可以实现集合的遍历

public class CollectionDemo3 {
    public static void main(String[] args) {
        //创建集合对象
        Collection c1 = new ArrayList();
​
        //添加元素
        c1.add("hello");
        c1.add("world");
        c1.add("java");
        c1.add("20");
//        c1.add(10);
​
        //将集合转换成数组
        Object[] array = c1.toArray();
​
        //遍历数组获取数组中每一个元素
        for (int i = 0; i < array.length; i++) {
//            System.out.println(array[i]);
            //因为获取到的元素类型是Object类型
            //所以没有length()方法
            //要想调用字符串中的length()方法,就需要进行向下转型
//            System.out.println(array[i].length());
​
            String s = (String) array[i];
            System.out.println(s + ",长度为:" + s.length());
        }
    }
}

 

需求2、向集合中添加3个学生对象,并遍历学生信息

public class CollectionDemo4 {
    public static void main(String[] args) {
        //创建集合
        Collection c1 = new ArrayList();
​
        //创建3个学生对象
        Student s1 = new Student("李玉伟", 18);
        Student s2 = new Student("刘生发", 17);
        Student s3 = new Student("朱佳乐", 16);
​
        //将学生对象添加到集合中
        c1.add(s1);
        c1.add(s2);
        c1.add(s3);
​
        //将学生对象集合转成数组
        Object[] array = c1.toArray();
​
        //遍历数组
        for (int i = 0; i < array.length; i++) {
            //向下转型,转成元素的类型
            Student s = (Student) array[i];
            System.out.println(s.getName() + "--" + s.getAge());
        }
​
    }
}

 

 

posted @ 2021-12-18 22:46  欧朋  阅读(51)  评论(0)    收藏  举报