import java.util.ArrayList;
import java.util.Collection;
/*
集合的遍历 操作
方式1.for循环的遍历
转换成数组,再去遍历
练习: 存储自定义对象 ,遍历 对象时,获取其属性值 ( 姓名,年龄 )
*/
public class CollectionDemo3 {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
Collection c = new ArrayList();
c.add("孙悟空");
c.add("白晶晶");
c.add("牛魔王");
c.add("红孩儿");
c.add("铁扇公主");
// 直接for,还不行 ,转成数组
Object[] array = c.toArray(); // 变成数组
for (int i = 0; i < array.length; i++) {
String s = (String) array[i]; // 直接转
System.out.println(s +"---"+s.length());
}
// for (int i = 0; i < c.size(); i++) {
// Object obj = array[i];
// String s = (String )obj; //向下强转
// System.out.println(s +"---"+s.length());
// }
}
}
|
|