import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class CollectionDemo01 { public static void main(String[] args) { Collection<String> c = new ArrayList<>(); c.add("赵敏"); c.add("小昭"); c.add("素素"); c.add("灭绝"); System.out.println(c); //[赵敏, 小昭, 素素, 灭绝] //使用迭代器遍历集合 Iterator<String> it = c.iterator(); //从集合对象中获取迭代器对象 // //next(): 获取当前位置元素,并将迭代器对象指向下一个元素处 // System.out.println(it.next()); // System.out.println(it.next()); // System.out.println(it.next()); // System.out.println(it.next()); // //System.out.println(it.next()); //产生异常 //2.使用循环结合迭代器遍历集合 //hasNext():判断当前访问位置是否有元素,若有则返回true while (it.hasNext()){ System.out.println(it.next()); } } }
import java.util.ArrayList; import java.util.Collection; public class CollectionDemo02 { public static void main(String[] args) { Collection<String> c = new ArrayList<>(); c.add("赵敏"); c.add("小昭"); c.add("素素"); c.add("灭绝"); System.out.println(c); //[赵敏, 小昭, 素素, 灭绝] /* 增强for循环: for(元素的数据类型 变量名: 数组或集合){ } */ //增强for遍历结合 for (String ele : c) { System.out.println(ele); } String[] names = {"迪丽热巴", "古力娜扎", "西起哈哈"}; //增强for遍历数组 for (String name: names){ System.out.println(name); } } }
import java.util.ArrayList; import java.util.Collection; public class CollectionDemo03 { public static void main(String[] args) { Collection<String> c = new ArrayList<>(); c.add("赵敏"); c.add("小昭"); c.add("素素"); c.add("灭绝"); System.out.println(c); //[赵敏, 小昭, 素素, 灭绝] //default void forEach(Consumer<? super T> action): 结合Lambda表达式遍历集合 c.forEach(s -> System.out.println(s)); } }