基礎——迭代器

迭代器接口與集合接口還有實現實現類的關係

在這裏插入圖片描述

爲什麼要用迭代的方式呢?

因爲我們知道Collection接口的其中一個子接口Set是沒有索引的,因此不能通過索引的方式來遍歷結合,故而引入了迭代器。

迭代器遍歷的原理

在這裏插入圖片描述
注意事項:

  1. 在進行集合元素獲取時,如果集合中已經沒有元素了,還繼續使用迭代器的next方法,將會拋出java.util.NoSuchElementException沒有集合元素異常。
  2. 在進行集合元素獲取時,如果添加或移除集合中的元素 , 將無法繼續迭代 , 將會拋出ConcurrentModificationException併發修改異常.

使用

Collection集合存儲整數並遍歷
步驟:

  1. 創建Collection集合對象,並添加數據,數據類型Integer
  2. 集合對象調用iterator方法,獲取迭代器Iterator接口的實現對象
  3. 循環遍歷
  4. 迭代器對象調用hasNext方法,判斷是否有下一個元素
  5. 如果有,迭代器對象調用next方法,獲取下一個元素
	public static void main(String[] args) {
        //1.創建Collection集合對象,並添加數據,數據類型Integer
        Collection<Integer> coll = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            coll.add(new Random().nextInt(100));
        }
        //2.集合對象調用iterator方法,獲取迭代器Iterator接口的實現對象
        Iterator<Integer> it = coll.iterator();
        while(it.hasNext()){
            Integer next = it.next();
            System.out.println(next);
        }
    }

增強for循環

迭代器的遍歷寫法十分繁瑣,所以JDK4.5以後版本引入了增強for循環,增強for循環在變異以後還是迭代器的寫法。

*.java文件

	public static void main(String[] args) {
        Collection<String> coll = new ArrayList<>();
        coll.add("C++");
        coll.add("Java");
        coll.add("php");
        coll.add("python");
        // 增強for循環
        for (String s : coll) {
            System.out.println(s);
        }
    }

*.class文件

public static void main(String[] args) {
        Collection<String> coll = new ArrayList();
        coll.add("C++");
        coll.add("Java");
        coll.add("php");
        coll.add("python");
        
        Iterator var3 = coll.iterator();

        while(var3.hasNext()) {
            String s = (String)var3.next();
            System.out.println(s);
        }
    }

注意事項:

  1. 增強for循環必須有被遍歷的目標,目標只能是Collection或者是數組;
  2. 增強for(迭代器)僅僅作爲遍歷操作出現,不能對集合進行增刪元素操作,否則拋出ConcurrentModificationException併發修改異常
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章