Java基礎 韓順平老師的 集合 的部分筆記

银河小船儿發表於2024-07-18

498,集合介紹

499,集合體系圖(兩個圖背下)

package com.hspedu.collection;

import java.util.ArrayList;
import java.util.HashMap;

public class Collection01 {
    public static void main(String[] args) {
        //老韓解讀
        //1,集合主要是兩組(單列集合,雙列集合)
        //2,Collection 介面有兩個重要的子介面 List Set,他們的實現子類都是單列集合
        //3,Map 介面的實現子類 是雙列集合,存放的 K-V
        //4,把老師梳理的兩張圖記住
        //Collection
        //Map

        //存放的資料是單個的,就是單列集合
        ArrayList arrayList = new ArrayList();
        arrayList.add("jack");

        //存放的資料是兩個的,就是雙列集合
        HashMap hashMap = new HashMap();
        hashMap.put("NO1","北京");
    }
}

500,Collection方法

package com.hspedu.collection;

import java.util.ArrayList;

import java.util.List;

public class Collection01 {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        List list = new ArrayList();
        //add:新增單個元素
        list.add("jack");
        list.add(10);//list.add(new Integer(10)),傳進的是一個物件
        list.add(true);
        System.out.println("list=" + list);

        //remove:刪除指定的元素
        //list.remove(0);//刪除第一個元素
        list.remove("jack");//指定刪除某個元素
        System.out.println("list=" + list);

        //contains:查詢元素是否存在
        System.out.println(list.contains(10));//T

        //size:獲取元素個數
        System.out.println(list.size());//2

        //isEmpty:判斷是否為空
        System.out.println(list.isEmpty());//F

        //clear:清空
        list.clear();
        System.out.println("list=" + list);

        //addAll:新增多個元素
        ArrayList list2 = new ArrayList();
        list2.add("紅樓夢");
        list2.add("三國演義");
        list.addAll(list2);
        System.out.println("list=" + list);

        //containsAll:查詢多個元素是否都存在
        System.out.println(list.containsAll(list2));//T

        //removeAll:刪除多個元素
        list.add("聊齋");
        list.removeAll(list2);
        System.out.println("list=" + list);//[聊齋]

    }
}

501,java迭代器遍歷

package com.hspedu.collection;

import java.util.ArrayList;

import java.util.Collection;
import java.util.Iterator;

public class Collection01 {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        Collection col = new ArrayList();//向上轉型,Collection是介面

        col.add(new Book("三國演義", "羅貫中", 10.1));
        col.add(new Book("小李飛刀", "古龍", 5.1));
        col.add(new Book("紅樓夢", "曹雪芹", 34.6));

        //System.out.println("col=" + col);
        //遍歷集合
        //1,先得到 col 對應的 迭代器
        Iterator iterator = col.iterator();
        //2,使用while迴圈遍歷,快捷鍵 itit
        while (iterator.hasNext()) { //判斷是否還有資料
            //返回下一個元素,型別是Object
            Object obj = iterator.next();
            System.out.println("obj=" + obj);
        }
        //3,當退出while迴圈後,這時iterator迭代器,指向最後的元素
        //iterator.next();//NoSuchElementException
        //4,如果希望再次遍歷,需要重置我們的迭代器
        iterator = col.iterator();
        System.out.println("===第二次遍歷===");
        while (iterator.hasNext()) {
            Object obj =  iterator.next();
            System.out.println("obj=" + obj);
        }
    }
}
class Book {
    private String name;
    private String author;
    private double price;

    public Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}

502,集合增強for

package com.hspedu.collection;

import java.util.ArrayList;

import java.util.Collection;
import java.util.Iterator;

public class Collection01 {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        Collection col = new ArrayList();//向上轉型,Collection是介面

        col.add(new Book("三國演義", "羅貫中", 10.1));
        col.add(new Book("小李飛刀", "古龍", 5.1));
        col.add(new Book("紅樓夢", "曹雪芹", 34.6));

        //老韓解讀
        //1,使用增強for迴圈,在Collection集合
        //2,增強for,底層仍然是迭代器
        //3,增強for可以理解成就是簡化版本的 迭代器遍歷
        //4,快捷鍵方式 I
        for(Object book : col) {
            System.out.println("book=" + book);
        }
    }
}
class Book {
    private String name;
    private String author;
    private double price;

    public Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}

503,測試題

package com.hspedu.collection;

import java.util.ArrayList;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class Collection01 {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(new Dog("小白",1));
        list.add(new Dog("小黑",2));
        list.add(new Dog("大黃",3));

        //使用迭代器遍歷
        System.out.println("===使用迭代器遍歷===");
        Iterator iterator = list.iterator();
        while(iterator.hasNext()) {
            Object d = iterator.next();
            System.out.println(d);
        }

        System.out.println("===使用for迴圈遍歷===");
        for(Object d : list) {
            System.out.println(d);
        }
    }
}
class Dog {
    private String name;
    private int age;

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "name:" + name + " " + "age=" + age;
    }
}

504,List介面方法

package com.hspedu.collection;

import java.util.ArrayList;

import java.util.List;

public class Collection01 {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
       //1,List集合類中元素有序(即新增順序和取出順序一致),且可重複
        List list = new ArrayList();
        list.add(1);
        list.add(1);
        list.add(3);
        list.add(4);
        System.out.println("list=" + list);
        //2,List集合中的每個元素都有其對應的順序索引,即支援索引
        //  索引是從0開始
        System.out.println(list.get(0));
    }
}

package com.hspedu.collection;

import java.util.ArrayList;

import java.util.List;

public class Collection01 {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("張三丰");
        list.add("賈寶玉");
        //1,void add(int index, Object ele):在index位置插入ele元素
        list.add(1,"劉備");
        System.out.println("list=" + list);

        //2,boolean addAll(int index, Collection eles):從index位置開始將eles中的所有元素新增進來
        List list1 = new ArrayList();
        list1.add(1);
        list1.add(2);
        list.addAll(1,list1);
        System.out.println("list=" + list);

        //3,int indexOf(Object obj):返回obj在集合中首次出現的位置
        System.out.println(list.indexOf("張三丰"));

        //4,int lastIndexOf(Object obj):返回obj在當前集合中末次出現的位置
        list.add(1);
        System.out.println("list=" + list);
        System.out.println(list.lastIndexOf(1));

        //5,Object remove(int index):移除指定index位置的元素,並返回此元素
        list.remove(0);
        System.out.println("list=" + list);

        //6,Object set(int index, Object ele):設定指定index位置的元素為ele,
        //  相當於是替換,index不能是最後一個位置和不存在的位置
        list.set(1,"瑪麗");
        System.out.println("list=" + list);

        //7,List subList(int fromIndex, int toIndex):返回從fromIndex到toIndex位置的子集合
        //  返回的子集合 fromIndex <= subList < toIndex
        List returnlist = list.subList(0,2);
        System.out.println("returnlist=" + returnlist);
    }
}

505,List介面練習

package com.hspedu.collection;

import java.util.ArrayList;

import java.util.Iterator;
import java.util.List;

public class Collection01 {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        List list = new ArrayList();
        for (int i = 0; i < 12; i++) {
            list.add("hello"+ i);
        }
        System.out.println("list=" + list);

        //在2號位插入一個元素"韓順平教育"
        list.add(1,"韓順平教育");
        System.out.println("list=" + list);

        //獲得第5個元素
        System.out.println("第5個元素=" + list.get(4));

        //刪除第6個元素
        list.remove(5);
        System.out.println("list=" + list);

        //修改第7個元素
        list.set(6, "三國演義");
        System.out.println("list=" + list);

        //使用迭代器遍歷
        Iterator iterator = list.iterator();
        while(iterator.hasNext()) {
            Object obj = iterator.next();
            System.out.println(obj);
        }
    }
}

506,List三種遍歷方式

package com.hspedu.collection;

import java.util.ArrayList;

import java.util.Iterator;
import java.util.List;

public class Collection01 {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("jack");
        list.add("tom");
        list.add("魚香肉絲");
        list.add("北京烤鴨");

        //遍歷
        //1,迭代器
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Object obj =  iterator.next();
            System.out.println(obj);
        }

        System.out.println("=====增強for=====");
        //2,增強for
        for (Object o : list) {
            System.out.println("o=" + o);
        }

        System.out.println("=====使用普通for=====");
        //3,使用普通for
        for (int i = 0; i < list.size(); i++) {
            System.out.println("物件=" + list.get(i));
        }
    }
}

507,List排序練習

package com.hspedu.collection;

import java.util.ArrayList;

import java.util.Iterator;
import java.util.List;
@SuppressWarnings({"all"})
public class Collection01 {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(new Book("紅樓夢","曹雪芹",100));
        list.add(new Book("西遊記","吳承恩",10));
        list.add(new Book("水滸傳","施耐庵",9));
        list.add(new Book("三國","羅貫中",80));
        list.add(new Book("西遊記","吳承恩",10));

        for (Object o : list) {
            System.out.println(o);
        }
        //氣泡排序
        sort(list);

        System.out.println("===排序後===");
        for (Object o : list) {
            System.out.println(o);
        }
    }
    //靜態方法
    //價格要求是從小到大
    public static void sort(List list) {
        int listSize = list.size();
        for (int i = 0; i < listSize - 1; i++) {
            for (int j = 0; j < listSize - 1 - i; j++) {
                //取出物件Book
                Book book1 = (Book)list.get(j); //list.get(j)返回的是Object物件,所以這裡強轉
                Book book2 = (Book)list.get(j+1);
                if(book1.getPrice() > book2.getPrice()) { //交換
                    list.set(j, book2);
                    list.set(j+1, book1);
                }
            }
        }
    }
}
class Book {
    private String name;
    private String author;
    private double price;

    public Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "名稱: " + name + "\t\t" + "價格: " + price + "\t\t" + "作者: " + author;
    }
}

508,ArrayList注意事項

package com.hspedu.collection;

import java.util.ArrayList;

import java.util.Iterator;
import java.util.List;
@SuppressWarnings({"all"})
public class Collection01 {
    public static void main(String[] args) {

        //ArrayList 是執行緒不安全的,可以看原始碼 沒有 synchronized(互斥的)
//        public boolean add(E e) {
//            modCount++;
//            add(e, elementData, size);
//            return true;
//        }

        ArrayList arrayList = new ArrayList();
        arrayList.add(null);
        arrayList.add("jack");
        arrayList.add(null);
        System.out.println(arrayList);
    }
}

509,ArrayLish擴容機制

自己補充序列化的知識點:

序列化是將Java物件轉變為位元組序列,便於持久化到本地磁碟,避免程式執行結束後物件從記憶體中消失,位元組序列也方便在網路中傳輸。

序列化的主要目的是透過網路傳輸物件或者說是將物件儲存到檔案系統、資料庫、記憶體中。

由於時間有限,從這以後的筆記只記自己理解的和敲的程式碼

514,雙向連結串列模擬

package com.hspedu.list_;

public class LinkedList {
    public static void main(String[] args) {
        //模擬一個簡單的雙向連結串列
        Node jack = new Node("jack");
        Node tom = new Node("tom");
        Node hsp = new Node("老韓");

        //連線三個節點,形成雙向連結串列
        //jack -> tom -> hsp
        jack.next = tom;
        tom.next = hsp;
        //hsp -> tom -> jack
        hsp.pre = tom;
        tom.pre = jack;

        Node first = jack;//讓first引用指向jack,就是雙向連結串列的頭節點
        Node last = hsp;//讓last引用指向hsp,就是雙向連結串列的尾節點

        //演示,從頭到尾進行遍歷
        System.out.println("===從頭到尾進行遍歷===");
        while (true) {
            if(first == null) {
                break;
            }
            //輸出first資訊
            System.out.println(first);
            first = first.next;
        }

        //演示,從尾到頭的遍歷
        System.out.println("===從尾到頭進行遍歷===");
        while (true) {
            if(last == null) {
                break;
            }
            //輸出last資訊
            System.out.println(last);
            last = last.pre;
        }

        //演示連結串列的新增物件/資料,是多麼的方便
        //要求,是在 tom-----老韓之間插入一個物件 smith

        //1,先建立一個 Node 節點,name 就是 smith
        Node smith = new Node("smith");
        //先改插入節點smith的指向
        smith.next = hsp;
        smith.pre = tom;
        //再改hsp,tom的指向
        hsp.pre = smith;
        tom.next = smith;

        //讓first 再次指向jack
        first = jack; //讓first引用指向jack,就是雙向連結串列的頭節點

        System.out.println("===從頭到尾進行遍歷===");
        while (true) {
            if(first == null) {
                break;
            }
            //輸出first資訊
            System.out.println(first);
            first = first.next;
        }
        
        
    }
}

//定義一個 Node 類, Node 物件 表示雙向連結串列的一個結點
class Node {
    public Object item;//真正存放資料
    public Node next;//指向後一個節點
    public Node pre;//指向前一個節點
    public Node(Object name) {
        this.item = name;
    }
    public String toString() {
        return "Node name=" + item;
    }
}

515,LinkedList增刪改查案例

package com.hspedu.list_;
import java.util.Iterator;
import java.util.LinkedList;

@SuppressWarnings({"all"})
public class LinkedListCRUD {
    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        linkedList.add(1);
        linkedList.add(2);
        linkedList.add(3);
        System.out.println("linkedList=" + linkedList);
        //演示一個刪除結點的
        linkedList.remove(); // 這裡預設刪除的是第一個結點
        //linkedList.remove(2);
        System.out.println("linkedList=" + linkedList);
        //修改某個結點物件
        linkedList.set(1, 999);
        System.out.println("linkedList=" + linkedList);
        //得到某個結點物件
        //get(1) 是得到雙向連結串列的第二個物件
        Object o = linkedList.get(1);
        System.out.println(o);//999
        //因為 LinkedList 是 實現了 List 介面, 遍歷方式
        System.out.println("===LinkeList 遍歷迭代器====");
        Iterator iterator = linkedList.iterator();
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println("next=" + next);
        }
        System.out.println("===LinkeList 遍歷增強 for====");
        for (Object o1 : linkedList) {
            System.out.println("o1=" + o1);
        }
        System.out.println("===LinkeList 遍歷普通 for====");
        for (int i = 0; i < linkedList.size(); i++) {
            System.out.println(linkedList.get(i));
        }
    }
}

517,Set介面方法

package com.hspedu.list_;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;

@SuppressWarnings({"all"})
public class SetMethod {
    public static void main(String[] args) {
        //1,以Set介面的實現類 HashSet來講解Set介面的方法
        //2. set 介面的實現類的物件(Set 介面物件), 不能存放重複的元素, 可以新增一個 null
        //3. set 介面物件存放資料是無序(即新增的順序和取出的順序不一致)
        Set set = new HashSet();
        set.add("john");
        set.add("lucy");
        set.add("john");//重複
        set.add("jack");
        set.add(null);//再次新增null
        //4. 注意: 取出的順序的順序雖然不是新增的順序, 但是他的固定.
        for(int i = 0; i < 3; i++) {
            System.out.println("set=" + set);
        }
        //遍歷
        //方式1:使用迭代器
        System.out.println("====使用迭代器====");
        Iterator iterator = set.iterator();
        while(iterator.hasNext()) {
            Object obj = iterator.next();
            System.out.println("obj=" + obj);
        }
        //方式2:增強for
        System.out.println("====增強for====");
        for(Object o : set) {
            System.out.println("o=" + o);
        }
        //set 介面物件, 不能透過索引來獲取,就是set.get[i]

    }
}

518,HashSet案例說明

package com.hspedu.list_;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;

@SuppressWarnings({"all"})
public class HashSet1 {
    public static void main(String[] args) {
        HashSet set = new HashSet();
        //1. 在執行 add 方法後, 會返回一個 boolean 值
        //2. 如果新增成功, 返回 true, 否則返回 false
        System.out.println(set.add("john"));//T
        System.out.println(set.add("lucy"));//T
        System.out.println(set.add("john"));//F
        System.out.println(set.add("jack"));//T
        System.out.println(set.add("Rose"));//T
        System.out.println("set=" + set);//5個
        //3. 可以透過 remove 指定刪除哪個物件
        set.remove("john");
        System.out.println("set=" + set);//3個

        set = new HashSet();
        System.out.println("set=" + set);//0
        //4 Hashset 不能新增相同的元素/資料?
        set.add("lucy");//新增成功
        set.add("lucy");//新增不了
        //兩個tom地址不一樣
        set.add(new Dog("tom"));
        set.add(new Dog("tom"));
        System.out.println("set=" + set);

        //在加深一下. 非常經典的面試題,看下節的HashMap底層 陣列連結串列模擬
        set.add(new String("hsp"));//ok
        set.add(new String("hsp"));//加入不了.
        System.out.println("set=" + set);
    }
}
//定義Dog類
class Dog {
    private String name;

    public Dog(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                '}';
    }
}

519,陣列連結串列模擬(HashSet底層機制是陣列+連結串列+紅黑樹)

package com.hspedu.list_;

@SuppressWarnings({"all"})
public class HashSetStructure {
    public static void main(String[] args) {
        //模擬一個HashSet的底層(HashSet的底層結構)
        //1,建立一個陣列,陣列的型別是 Node[]
        //2,有些人,直接把 Node[] 陣列稱為 表
        Node[] table = new Node[16];
        System.out.println("table=" + table);
        //3,建立節點
        Node john = new Node("john", null);

        //把lucy放到table表的索引為2的位置
        table[2] = john;
        Node jack = new Node("jack", null);
        //將jack節點掛載到john
        john.next = jack;
        Node rose = new Node("Rose", null);
        //將rose節點掛載到jack
        jack.next = rose;
        Node lucy = new Node("lucy", null);
        //把lucy放到table表的索引為3的位置
        table[3] = lucy;
        System.out.println("table=" + table);

    }
}
//節點,儲存資料,可以指向下一個節點,從而形成連結串列
class Node {
    Object item; //存放資料
    Node next; //指向下一個節點

    public Node(Object item, Node next) {
        this.item = item;
        this.next = next;
    }
}

表的結構

525,HashSet最佳實踐

package com.hspedu.list_;

import java.util.*;

@SuppressWarnings({"all"})
public class Map_ {
    public static void main(String[] args) {
        HashSet hashSet = new HashSet();
        hashSet.add(new Employee("milan", 18));
        hashSet.add(new Employee("smith", 28));
        hashSet.add(new Employee("milan", 18));

        System.out.println("hashSet=" + hashSet);

    }
}
class Employee {
    private String name;
    private int age;

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    //重寫 equals 方法 和 hashCode, 快捷鍵 fn+Alt+Insert 選 equals()' and 'hashCode()'
    //當 name 和 price 相同時, 就返回相同的 hashCode 值, equals 返回 true

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return age == employee.age && Objects.equals(name, employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

529,LHashSet課堂練習

package com.hspedu.list_;

import java.util.*;

@SuppressWarnings({"all"})
public class Map_ {
    public static void main(String[] args) {
        LinkedHashSet linkedHashSet = new LinkedHashSet();
        linkedHashSet.add(new Car("奧拓", 1000));//OK
        linkedHashSet.add(new Car("奧迪", 300000));//OK
        linkedHashSet.add(new Car("法拉利", 10000000));//OK
        linkedHashSet.add(new Car("奧迪", 300000));//加入不了
        linkedHashSet.add(new Car("保時捷", 70000000));//OK
        linkedHashSet.add(new Car("奧迪", 300000));//加入不了
        System.out.println("linkedHashSet=" + linkedHashSet);

    }
}
class Car {
    private String name;
    private int price;

    public Car(String name, int price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "\nCar{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Car car = (Car) o;
        return price == car.price && Objects.equals(name, car.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, price);
    }
}

530,Map介面特點1

package com.hspedu.list_;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings({"all"})
public class Map_ {
    public static void main(String[] args) {
        //Map 介面實現類的特點,使用實現類HashMap
        //1,Map與Collection並列存在,用於儲存具有對映關係的資料:Key-Value(雙列元素)
        //2,Map中的key和value可以是任何引用型別的資料,會封裝到HashMap$Node物件中

        Map map = new HashMap();
        map.put("no1", "韓順平");//k-v
        map.put("no2", "張無忌");
        //3,Map中的key不允許重複,原因和HashSet 一樣,前面分析過原始碼。底層會用 equals函式
        map.put("no1", "張三丰");//當有相同的k,就等價於替換
        //4,Map中的value可以重複
        map.put("no3", "張三丰");
        //5,Map的key可以為null,value也可以為null,注意key為null,只能有一個,value為null,可以多個
        map.put(null, null);
        map.put(null, "abc");//等價替換
        map.put("no4", null);
        map.put("no5", null);
        map.put(1, "趙敏");
        map.put(new Object(), "金毛獅王");
        //6,常用的String類作為Map的key
        //7,key和value之間存在單向一對一關係,即透過指定的key總能找到對應的value
        //透過get方法,傳入key,會返回對應的value
        System.out.println(map.get("no2"));//張無忌

        System.out.println("map=" + map);

    }
}

532,Map介面方法

package com.hspedu.list_;

import java.util.*;

@SuppressWarnings({"all"})
public class Map_ {
    public static void main(String[] args) {
        //演示 map 介面常用方法
        //put:新增
        Map map = new HashMap();
        map.put("鄧超", new Book("", 100));//OK
        map.put("鄧超", "孫儷");//替換-> 一會分析原始碼
        map.put("王寶強", "馬蓉");//OK
        map.put("宋喆", "馬蓉");//OK
        map.put("劉令博", null);//OK
        map.put(null, "劉亦菲");//OK
        map.put("鹿晗", "關曉彤");//OK
        map.put("hsp", "hsp 的老婆");
        System.out.println("map=" + map);

        //remove:根據鍵刪除對映關係
        map.remove(null);
        System.out.println("map=" + map);
        //get:根據鍵獲取值
        Object val = map.get("鹿晗");
        System.out.println("val=" + val);
        //size:獲取元素個數
        System.out.println("k-v鍵值對的數量=" + map.size());
        //isEmpty:判斷個數是否為0
        System.out.println(map.isEmpty());
        //clear:清空k-v
        //map.clear();
        System.out.println("map=" + map);
        //containsKey:查詢鍵是否存在
        System.out.println(map.containsKey("hsp"));

    }
}
class Book {
    private String name;
    private int num;
    public Book(String name, int num) {
        this.name = name;
        this.num = num;
}
}

533,Map六大遍歷方式

package com.hspedu.list_;

import java.util.*;

@SuppressWarnings({"all"})
public class Map_ {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("鄧超", "孫儷");
        map.put("王寶強", "馬蓉");
        map.put("宋喆", "馬蓉");
        map.put("劉令博", null);
        map.put(null, "劉亦菲");
        map.put("鹿晗", "關曉彤");
        System.out.println("map=" + map);

        //第一組: 先取出 所有的 Key , 透過 Key 取出對應的 Value
        Set keyset = map.keySet();
        //(1) 增強 for
        System.out.println("------第一種方式------");
        for(Object key : keyset) {
            System.out.println(key + "-" + map.get(key));
        }
        //(2) 迭代器
        System.out.println("----第二種方式--------");
        Iterator iterator = keyset.iterator();
        while (iterator.hasNext()) {
            Object key = iterator.next();
            System.out.println(key + "-" + map.get(key));
        }

        //第二組: 把所有的 values 取出
        Collection values = map.values();
        //這裡可以使用所有的 Collections 使用的遍歷方法
        //(1) 增強 for
        System.out.println("---取出所有的 value 增強 for----");
        for (Object value : values) {
            System.out.println(value);
        }
        //(2) 迭代器
        System.out.println("---取出所有的 value 迭代器----");
        Iterator iterator1 = values.iterator();
        while(iterator1.hasNext()) {
            Object value = iterator1.next();
            System.out.println(value);
        }

        //第三組: 透過 EntrySet 來獲取 k-v
        Set entrySet = map.entrySet();// EntrySet<Map.Entry<K,V>>
        //(1) 增強 for
        System.out.println("----使用 EntrySet 的 for 增強(第 3 種)----");
        for (Object entry : entrySet) {
            //將 entry 轉成 Map.Entry
            Map.Entry m = (Map.Entry) entry;//向下轉型,因為要從EntrySet中取到Map.Entry
            System.out.println(m.getKey() + "-" + m.getValue());
        }
        //(2) 迭代器
        System.out.println("----使用 EntrySet 的 迭代器(第 4 種)----");
        Iterator iterator2 = entrySet.iterator();
        while (iterator2.hasNext()) {
            Object entry = iterator2.next();
            //System.out.println(entry.getClass());//HashMap$Node -實現-> Map.Entry (getKey,getValue)
            //向下轉型 Map.Entry
            Map.Entry m = (Map.Entry) entry;
            System.out.println(m.getKey() + "-" + m.getValue());
        }
    }
}

534,Map課堂練習

package com.hspedu.list_;

import java.util.*;

@SuppressWarnings({"all"})
public class Map_ {
    public static void main(String[] args) {
        Map hashMap = new HashMap();
        //新增物件
        hashMap.put(1, new Emp("jack", 300000, 1));
        hashMap.put(2, new Emp("tom", 21000, 2));
        hashMap.put(3, new Emp("milan", 12000, 3));

        //遍歷 2 種方式
        //並遍歷顯示工資>18000 的員工(遍歷方式最少兩種)
        //1. 使用 keySet -> 增強 for
        Set keySet = hashMap.keySet();
        System.out.println("====第一種遍歷方式====");
        for (Object key : keySet) {
            //先獲取 value,因為要遍歷顯示工資>18000 的員工,value是Emp物件,所以下面要轉成Emp
            Emp emp = (Emp) hashMap.get(key);
            if (emp.getSal() > 18000) {
                System.out.println(emp);
            }
        }

        //2. 使用 EntrySet -> 迭代器
        // 體現比較難的知識點
        // 慢慢品, 越品越有味道.
        Set entrySet = hashMap.entrySet();
        System.out.println("======迭代器======");
        Iterator iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry)iterator.next();
            //透過 entry 取得 key 和 value
            Emp emp = (Emp) entry.getValue();
            if (emp.getSal() > 18000) {
                System.out.println(emp);
            }
        }
        
    }
}
class Emp {
    private String name;
    private double sal;
    private int id;

    @Override
    public String toString() {
        return "Emp{" +
                "name='" + name + '\'' +
                ", sal=" + sal +
                ", id=" + id +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSal() {
        return sal;
    }

    public void setSal(double sal) {
        this.sal = sal;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Emp(String name, double sal, int id) {
        this.name = name;
        this.sal = sal;
        this.id = id;
    }
}

542,總結-開發中如何選擇集合實現類(記住)

545,Collections工具類

package com.hspedu.list_;

import java.util.*;
import java.util.concurrent.CompletionService;

@SuppressWarnings({"all"})
public class Map_ {
    public static void main(String[] args) {
        //建立 ArrayList 集合, 用於測試
        List list = new ArrayList();
        list.add("tom");
        list.add("smith");
        list.add("king");
        list.add("milan");
        list.add("tom");

        //reverse(List): 反轉 List 中元素的順序
        Collections.reverse(list);
        System.out.println("list=" + list);
        //shuffle(List): 對 List 集合元素進行隨機排序
        Collections.shuffle(list);
        System.out.println("list=" + list);
        //sort(List): 根據元素的自然順序對指定 List 集合元素按升序排序
        Collections.sort(list);
        System.out.println("sort排序後");
        System.out.println("list=" + list);
        //sort(List, Comparator): 根據指定的 Comparator 產生的順序對 List 集合元素進行排序
        //我們希望按照 字串的長度大小排序
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o1).length() - ((String)o2).length();
            }
        });
        System.out.println("字串長度大小排序=" + list);
        // swap(List, int, int): 將指定 list 集合中的 i 處元素和 j 處元素進行交換
        Collections.swap(list, 0, 1);
        System.out.println("交換後的情況");
        System.out.println("list=" + list);

        //Object max(Collection): 根據元素的自然順序, 返回給定集合中的最大元素
        System.out.println("自然順序最大元素=" + Collections.max(list));
        //Object max(Collection, Comparator): 根據 Comparator 指定的順序, 返回給定集合中的最大元素
        //比如, 我們要返回長度最大的元素
        Object maxObject = Collections.max(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o1).length() - ((String)o2).length();
            }
        });
        System.out.println("長度最大的元素=" + maxObject);
        //Object min(Collection)
        //Object min(Collection, Comparator)
        //上面的兩個方法, 參考 max 即可

        //int frequency(Collection, Object): 返回指定集合中指定元素的出現次數
        System.out.println("tom出現的次數=" + Collections.frequency(list, "tom"));

        //void copy(List dest,List src): 將 src 中的內容複製到 dest 中
        ArrayList dest = new ArrayList();
        //為了完成一個完整複製, 我們需要先給 dest 賦值, 大小和 list.size()一樣,因為dest初始長度是0
        for(int i = 0; i < list.size(); i++) {
            dest.add("");
        }
        //複製
        Collections.copy(dest, list);
        System.out.println("dest=" + dest);

        //boolean replaceAll(List list, Object oldVal, Object newVal): 使用新值替換 List 物件的所有舊值
        //如果 list 中, 有 tom 就替換成 湯姆
        Collections.replaceAll(list, "tom", "湯姆");
        System.out.println("list替換後=" + list);

    }
}

547,集合家庭作業1

package com.hspedu.list_;

import java.util.*;
import java.util.concurrent.CompletionService;

@SuppressWarnings({"all"})
public class Map_ {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        arrayList.add(new News("新冠確診病例超千萬,數百萬印度教信徒赴恆河\"聖浴\"引民眾擔憂"));
        arrayList.add(new News("男子突然想起2個月前釣的魚還在網兜裡,撈起一看趕緊放生"));

        int size = arrayList.size();
        for (int i = size - 1; i >= 0; i--) {
            //System.out.println(arrayList.get(i));
            News news = (News) arrayList.get(i);
            System.out.println(processTitle(news.getTitle()));
        }
    }
    //專門寫一個方法,處理現實新聞標題
    public static String processTitle(String title) {
        if (title == null) {
            return "";
        }
        if(title.length() > 15) {
            return title.substring(0,15) + "...";
        }else {
            return title;
        }
    }
}

class News {
    private String title;
    private String content;

    public News(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "News{" +
                "title='" + title + '\'' +
                '}';
    }
}

548,集合家庭作業2

package com.hspedu.list_;

import java.util.*;
import java.util.concurrent.CompletionService;

@SuppressWarnings({"all"})
public class Map_ {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        Car car = new Car("寶馬", 400000);
        Car car2 = new Car("賓利", 5000000);
        arrayList.add(car);
        arrayList.add(car2);
        System.out.println(arrayList);
        arrayList.remove(car);
        System.out.println(arrayList);
        System.out.println(arrayList.contains(car));//F
        System.out.println(arrayList.size());//1
        System.out.println(arrayList.isEmpty());//F
        arrayList.addAll(arrayList);//2個賓利
        System.out.println(arrayList);
        System.out.println(arrayList.containsAll(arrayList));
        //arrayList.removeAll(arrayList);//相當於清空
        System.out.println("----遍歷----");
        for (Object o : arrayList) {
            System.out.println(o);
        }
        Iterator iterator = arrayList.iterator();
        while(iterator.hasNext()) {
            Object next  = iterator.next();
            System.out.println(next);
        }

    }
}
class Car {
    private String name;
    private double price;

    public Car(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

549,集合家庭作業3

package com.hspedu.list_;

import java.util.*;
import java.util.concurrent.CompletionService;

@SuppressWarnings({"all"})
public class Map_ {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("jack", 650);
        map.put("tom", 1200);
        map.put("smith", 2900);
        System.out.println(map);

        map.put("jack", 2600);//替換
        System.out.println(map);

        //為所有員工工資加薪100元
        //先取出key,用keySet
        Set keySet = map.keySet();
        for(Object key : keySet) {
            //透過key更新value
            map.put(key, (Integer)map.get(key) + 100);
        }
        System.out.println(map);

        //遍歷 EntrySet
        System.out.println("---EntrySet 迭代器遍歷 ---");
        Set entrySet = map.entrySet();
        Iterator iterator = entrySet.iterator();
        while(iterator.hasNext()) {
            Map.Entry entry = (Map.Entry)iterator.next();
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }

        System.out.println("----遍歷所有的工資----");
        Collection values = map.values();
        for (Object value : values) {
            System.out.println("工資=" + value);
        }

    }
}

相關文章