Java學習日誌(三): Colletion接口,迭代器Iterator接口,增強for循環

JavaEE學習日誌持續更新----> 必看!JavaEE學習路線(文章總彙)

今天學習了Colletion接口(集合),迭代器,增強for循環

Collection接口(集合)

java.util包中

集合與數組的區別

數組:

  • 長度固定 new int[3]{1,2,3,4}
  • 可以存儲基本類型數據,int[] double[]
  • 可以存儲引用類型的數據, Person[]

集合:

  • 長度可以變化 add()長度+1 remove()長度-1
  • 只能存儲引用類型的數據 ArrayList ArrayList

繼承與實現關係

在這裏插入圖片描述

Collection常用方法

  • public boolean add(E e) : 把給定的對象添加到當前集合中 。
  • public void clear() :清空集合中所有的元素。
  • public boolean remove(E e) : 把給定的對象在當前集合中刪除。
  • public boolean contains(Object obj) : 判斷當前集合中是否包含給定的對象。
  • public boolean isEmpty() : 判斷當前集合是否爲空。
  • public int size() : 返回集合中元素的個數。
  • public Object[] toArray() : 把集合中的元素,存儲到數組中
import java.util.ArrayList;
import java.util.Collection;

public class Demo01 {
    public static void main(String[] args) {
        //多態
        Collection<String> coll = new ArrayList<>();
        coll.add("張三");
        coll.add("李四");
        coll.add("aaa");
        coll.add("張三");
        coll.add("ccc");
        //集合重寫了toString方法
        System.out.println(coll);

        /*
         *   public boolean remove(E e) : 把給定的對象在當前集合中刪除。
         *       如果集合中有對應的元素,移除元素,返回true
         *       沒有的話,不會對集合產生影響,返回false
         *       如果有多個元素,只移除第一個
         * */
        boolean b1 = coll.remove("張三");
        System.out.println(b1);
        boolean b2 = coll.remove("張aaa");
        System.out.println(b2);
        System.out.println(coll);

        /*
         * public boolean contains(Object obj) : 判斷當前集合中是否包含給定的對象。
         *   包含返回true
         *   不包含返回false
         * */
        boolean b3 = coll.contains("aaa");
        System.out.println(b3);
        boolean b4 = coll.contains("aaaa");
        System.out.println(b4);

        /*
        * public int size() : 返回集合中元素的個數。
        * */
        System.out.println(coll.size());//4

        /*
        * public Object[] toArray() : 把集合中的元素,存儲到數組中
        * */
        Object[] arr = coll.toArray();
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
        /*
        * public boolean isEmpty() : 判斷當前集合是否爲空。
        *   集合爲空,返回true
        *   集合不爲空,返回false
        * */
        System.out.println(coll.isEmpty());//false
        /*
        * public void clear() :清空集合中所有的元素。
        *   集合還存在,元素被清空
        * */
        coll.clear();
        System.out.println(coll);//[]
        System.out.println(coll.isEmpty());//true
    }
}

Iterator接口(迭代器)

java.util.Iterator

迭代器

由來:

  • 集合有很多種,每種集合存儲數據的原理不同,取出元素的方式也不同,
    所以我們可以使用迭代器,來取出元素,是一種通用的取出集合中元素的方式.

原理::

  • 即Collection集合元素的通用獲取方式。在取元素之前先要判斷集合中有沒有元素,如果有,就把這個 元素取出來,繼續在判斷,如果還有就再取出出來。一直把集合中的所有元素全部取出。這種取出方式專業術語稱爲迭代

迭代器的使用:

  • Collection集合中有一個方法 iterator(),返回了Iterator接口的實現類對象Iterator iterator() 返回此集合中元素的迭代器。

瞭解:迭代器的實現類是每個集合的內部類

hasNext()與next()

成員方法:

  • boolean hasNext() 如果迭代具有更多元素,則返回 true 。
  • E next() 返回迭代中的下一個元素。

使用步驟

迭代器的使用步驟:

  1. 創建集合對象,在集合中添加元素
  2. 使用集合的方法iterator獲取迭代器的對象
  3. 使用迭代器Iterator中的方法hasNext和next依次取出集合中的元素

注意:若集合中已經沒有元素,繼續迭代,會報NoSuchElementException異常

public class Demo02Interator {
    public static void main(String[] args) {
//        1.創建集合對象,在集合中添加元素
        Collection<String> coll = new ArrayList<>();
        coll.add("aaa");
        coll.add("bbb");
        coll.add("ccc");
        coll.add("ddd");
        coll.add("eee");

/*
*         2.使用集合的方法iterator獲取迭代器的對象
*         迭代器的泛型跟着集合走
* */
        Iterator<String> it = coll.iterator();
//        3.使用迭代器Iterator中的方法hasNext和next依次取出集合中的元素
        /*boolean b = it.hasNext();
        System.out.println(b);//true
        String s = it.next();
        System.out.println(s); //aaa

        b = it.hasNext();
        System.out.println(b);//true
        s = it.next();
        System.out.println(s);//bbb

        b = it.hasNext();
        System.out.println(b);//true
        s = it.next();
        System.out.println(s);//ccc

        b = it.hasNext();
        System.out.println(b);//true
        s = it.next();
        System.out.println(s);//ddd

        b = it.hasNext();
        System.out.println(b);//false
        s = it.next();
        System.out.println(s);//eee

        b = it.hasNext();
        System.out.println(b);//沒有元素,再取出NoSuchElementException
        s = it.next();
        System.out.println(s);*/

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

    }
}

併發修改異常

ConcurrentModificationException
產生的原因:在使用迭代器遍歷集合的過程中,對集合的長度進行了修改(增加或刪除元素)
併發:遍歷和修改同時進行
在這裏插入圖片描述
解決方法:

  1. 不對集合進行修改
  2. 想要修改,可以使用Iterator接口的子接口ListIterator
public interface ListIterator<E> extends Iterator<E>{
//裏面定義了往集合中添加元素和刪除元素的方法
 	void add​(E e){} //將指定的元素插入列表(可選操作)。
      	void remove(){} //從列表中刪除 next()或 previous() (可選操作)返回的最後一個元素。

}

注意:ListIterator接口只能遍歷list接口下邊的集合

public class Demo03 {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        list.add("ddd");
        list.add("eee");
//        獲取迭代器對象
        Iterator<String> it = list.iterator();
//        取出元素
        while(it.hasNext()){
            String s = it.next();
            System.out.println(s);
            /*
            * 增加一個判斷,如果存在aaa,就增加hhh
            *
            * */
            /*if(s.equals("aaa")){
                list.add("hhh");	//ConcurrentModificationException
            }*/
//            list.remove(s);	//ConcurrentModificationException
        }
        System.out.println("---------------------");
        //        使用ListIterator方法獲取迭代器對象
        ListIterator<String> lit = list.listIterator();
        while(lit.hasNext()){
            String s = lit.next();
            System.out.println(s);
            if(s.equals("aaa")){
                lit.add("hhh");//使用迭代器增加元素的方法
            }
        }
        System.out.println(list);
    }
}

增強for循環

JDK1.5之後出現的新特性,底層就是一個迭代器,使用for循環的格式簡化了迭代器的代碼
作用:只要遍歷都用增強for!!!

  1. 可以遍歷數組
  2. 可以遍歷集合

格式:

for(集合/數組中的元素數據類型 變量名:集合名/數組名){
	sout(變量名);
}

使用增強for遍歷數組

private static void show01() {
    int[] arr = {1, 2, 3};
    for (int a : arr) {
        System.out.println(a);
    }
}

增強for循環遍歷的同時,可以使用元素特有的方法

/*
 * 增強for循環遍歷的同時,可以使用元素特有的方法
 * */
private static void show03() {
    String[] arr = {"111", "222", "333"};
    for (String s : arr) {
        System.out.println(s.length());
    }
}

增強for遍歷集合

private static void show04() {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(null);//用int可能會報空指針異常
        list.add(3);
        list.add(4);
//        for (int i : list) {//自動拆箱,用int可能會報空指針異常
//            System.out.println(i);
//        }
        for (Integer in : list) {
            System.out.println(in);
        }
    }

增強for和普通for的區別

普通for:在遍歷的過程中可以對數組或集合中的元素進行修改(索引修改)
增強for:沒有索引,不能修改數組或集合中的元素
原理:在這裏插入圖片描述

private static void show02() {
    int[] arr1 = {1, 2, 3};
    //普通for
    for (int i = 0; i < arr1.length; i++) {
        //把數組中的元素擴大二倍
        arr1[i] *= 2;//擴大的是數組的值
        System.out.println(arr1[i]);
    }
    //修改了
    System.out.println("arr1[0]" + arr1[0]);
    System.out.println("-------------------");
    int[] arr2 = {1, 2, 3};
    //增強for     ---->arr2.for 快捷鍵
    for (int i : arr2) {
        //把數組中的元素擴大二倍
        i *= 2;//擴大的是i的值,原數組沒變
        System.out.println(i);
    }
    //沒有被修改!!!!!!!!!!!!!!!!!
    System.out.println("arr2[0]" + arr2[0]);
}
發佈了25 篇原創文章 · 獲贊 33 · 訪問量 5973
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章