Java基础知识强化之集合框架笔记12:Collection集合存储字符串并遍历

1.  Collection集合存储字符串并遍历

分析:

(1)创建集合对象

(2)创建字符串对象

(3)把字符串对象添加到集合中

(4)遍历集合

2. 代码示例:

 1 package cn.itcast_04;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 import java.util.Iterator;
 6 
 7 /*
 8  * 需求:存储字符串并遍历。
 9  * 
10  * 分析:
11  *         A:创建集合对象
12  *         B:创建字符串对象
13  *         C:把字符串对象添加到集合中
14  *         D:遍历集合
15  */
16 public class CollectionTest {
17     public static void main(String[] args) {
18         // 创建集合对象
19         Collection c = new ArrayList();
20 
21         // 创建字符串对象
22         // 把字符串对象添加到集合中
23         c.add("林青霞");
24         c.add("风清扬");
25         c.add("刘意");
26         c.add("武鑫");
27         c.add("刘晓曲");
28 
29         // 遍历集合
30         // 通过集合对象获取迭代器对象
31         Iterator it = c.iterator();
32         // 通过迭代器对象的hasNext()方法判断有没有元素
33         while (it.hasNext()) {
34             // 通过迭代器对象的next()方法获取元素
35             String s = (String) it.next();
36             System.out.println(s);
37         }
38     }
39 }

运行结果如下:

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