集合转数组遍历。

package com.heima.collection;

import java.util.ArrayList;
import java.util.Collection;

import com.heima.bean.Student;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class Demo03 {
public static void main(String[] args) {
test01();
Collection c = new ArrayList();
c.add(new Student("张三", 23));// Object obj = new Student("张三",23);
c.add(new Student("李四", 21));
c.add(new Student("王五", 22));
Object[] arr = c.toArray();// 将集合转换成数组
for (int i = 0; i < arr.length; i++) {
// 写法一:
System.out.println(arr[i]);
// 写法二:
Student s = (Student) arr[i];// 将object类型转换为student类型
System.out.println(s.getAge());
/*
* 这两种写法区别:写法一是直接打印,写法二可以打印也可以获取到属性值,其他地方也可以利用(存储)。
*/
}
}

private static void test01() {
Collection c = new ArrayList();
c.add("a");
c.add("a");
c.add("a");
c.add("a");
Object[] arr = c.toArray(); // 将集合转换成数组
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}

原文地址:https://www.cnblogs.com/wangffeng293/p/14203914.html