Java基础知识强化之集合框架笔记05:Collection集合的遍历

1.Collection集合的遍历

Collection集合直接是不能遍历的,所以我们要间接方式才能遍历,我们知道数组Array方便实现变量,我们可以这样:

使用Object[]  toArray():把集合转化成数组,可以实现集合的遍历

代码实现:

 1 package cn.itcast_01;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 
 6 /*
 7  * 集合的遍历。其实就是依次获取集合中的每一个元素。
 8  * 
 9  * Object[] toArray():把集合转成数组,可以实现集合的遍历
10  */
11 public class CollectionDemo3 {
12     public static void main(String[] args) {
13         // 创建集合对象
14         Collection c = new ArrayList();
15 
16         // 添加元素
17         c.add("hello"); // Object obj = "hello"; 向上转型
18         c.add("world");
19         c.add("java");
20 
21         // 遍历
22         // Object[] toArray():把集合转成数组,可以实现集合的遍历
23         Object[] objs = c.toArray();
24         for (int x = 0; x < objs.length; x++) {
25             // System.out.println(objs[x]);
26             // 我知道元素是字符串,我在获取到元素的的同时,还想知道元素的长度。
27             // System.out.println(objs[x] + "---" + objs[x].length());
28             // 上面的实现不了,原因是Object中没有length()方法
29             // 我们要想使用字符串的方法,就必须把元素还原成字符串
30             // 向下转型
31             String s = (String) objs[x];
32             System.out.println(s + "---" + s.length());
33         }
34     }
35 }

运行效果如下:

原文地址:https://www.cnblogs.com/hebao0514/p/4851405.html