JAVA中集合的迭代遍历 接口iterator()

    技术2022-07-11  76

    JAVA中集合的迭代/遍历方法

    以下讲解的遍历方式/迭代方式,是所有Collection通用的一种方式

    在Map集合中不能使用,在所有的Collection以及子类中使用

    第一步:创建迭代器对象: Iterator it = e.iterator();

    第二步:通过以上获取的迭代器对象开始迭代/遍历集合 以下两个方法为迭代器中的方法: ------ boolean hasNext() 如果集合中仍有元素可迭代,返回true ------ Object next() 让迭代器前进一位,并返回迭代器指向的元素

    import java.util.Collection; import java.util.HashSet; import java.util.Iterator; public class CollectionTest02 { public static void main(String[] args) { //注意:以下讲解的遍历方式/迭代方式,是所有Collection通用的一种方式 //在Map集合中不能使用,在所有的Collection以及子类中使用 //创建集合对象: Collection e = new HashSet(); //HashSet存进去是无序的,存和取的顺序可能不一样 //添加元素 e.add("abc"); e.add("def");//HashSet不可以重复,但重复不会报错 e.add(100); e.add(new Object()); //第一步:创建迭代器对象: Iterator it = e.iterator(); //第二步:通过以上获取的迭代器对象开始迭代/遍历集合 /* 以下两个方法为迭代器中的方法: boolean hasNext() 如果集合中仍有元素可迭代,返回true Object next() 让迭代器前进一位,并返回迭代器指向的元素 */ while (it.hasNext()){ Object obj = it.next(); if (obj instanceof Integer){ System.out.println("==========Integer有的============"); } System.out.println(obj); //迭代器中it最初并没有指向第一个元素 } } } //运行结果: java.lang.Object@10f87f48 abc def ==========Integer有的============ 100

    当集合发生变化后,迭代器需重新获取:

    import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class CollectionTest05 { public static void main(String[] args) { Collection c = new ArrayList(); /* 注意:此时的获取的迭代器指向的是集合中没有元素状态下的迭代器 一定要注意:集合结构只要发生改变,迭代器必须重新获取 */ // Iterator it = c.iterator(); c.add("abcd"); c.add(100); // while(it.hasNext()){ // Object o = it.next(); // System.out.println(o); // } //当集合发生改变,而迭代器又没有重新获取时, //调用next方法时会发生异常: //java.util.ConcurrentModificationException Iterator it2 = c.iterator(); //应重新获取迭代器 //遍历集合 while(it2.hasNext()){ Object o = it2.next(); System.out.println(o); } } }
    Processed: 0.017, SQL: 9