集合框架_ArrayList存储字符串并遍历增强for版

来源:互联网 发布:小提琴入门 知乎 编辑:程序博客网 时间:2024/05/16 09:11
package cn.itcast_01;import java.util.ArrayList;import java.util.Iterator;/* * ArrayList存储字符串并遍历。要求加入泛型,并用增强for遍历。 * A:迭代器 * B:普通for * C:增强for */public class ArrayListDemo {public static void main(String[] args) {// 创建集合对象ArrayList<String> array = new ArrayList<String>();// 添加元素array.add("hello");array.add("world");array.add("java");array.add("android");// 遍历// 增强forif (array != null) {for (String s : array) {System.out.println(s);}}System.out.println("-------------------");// 普通forfor (int x = 0; x < array.size(); x++) {String s = array.get(x);System.out.println(s);}System.out.println("-------------------");// 迭代器Iterator<String> it = array.iterator();while(it.hasNext()){String s = it.next();System.out.println(s);}}}

0 0