迭代器 iterator

    xiaoxiao2021-04-15  229

    @Test public void test03() { Collection col = new ArrayList(); col.add(“jarry”); col.add(“lucy”); col.add(“jarry”); col.add(“tom”); col.add(“jack”); col.add(“rose”); col.add(“jarry”); col.remove(“jarry”); //移除 System.out.println(col); // 迭代集合,获取集合中的每一个元素 // 1.获得迭代器 Iterator it = col.iterator(); // 2.循环 while (it.hasNext()) { // 获得迭代器中当前元素 String str = it.next(); if (str.equals(“jarry”)) { // ConcurrentModificationException – 风险警告 // 在迭代器内部,不能使用集合自己的移除方法 // col.remove(str); // 只能使用迭代器提供的移除方法 it.remove(); } System.out.println(str); } System.out.println(col); }

    @Test public void test04() { Collection col = new ArrayList(); col.add(“jarry”); col.add(“lucy”); col.add(“jarry”); col.add(“tom”); col.add(“jack”); col.add(“rose”); col.add(“jarry”);

    // foreach 简易版Iterator // 只能迭代访问,不能迭代删除 for (String str : col) { // String str = it.next(); System.out.println(str); } int[] arr = { 1, 2, 3, 4, 5 }; for (int a : arr) { System.out.println(a); } }

    最新回复(0)