Cher ZY
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    :::info <a href="/@TFA101/CherryJava" target="_self"> < :notebook_with_decorative_cover: [共享目錄] Java 2 學習筆記</a> ::: # 模組13-15 集合(Collection) 一群相關的資料,集合在一起組成一個**物件**,存在物件中的資料稱為元素(Element)。 ## 集合與陣列 同為可以存取一群資料的物件,集合的彈性比陣列高。 運用多型(Polymorphism)概念,所有物件都提升為Object,集合就什麼都可以放,基本型別原本不屬於物件,也會跟著自動裝箱(Auto-boxing)。 反過來也有泛型(Generic)可以限制存放的型別,而且還有上下邊界限制的存放方式 `<? extends Superclass>` 和 `<? super Subclass>`,分別限制存放物件類別的父類別與子類別,更加具有操作彈性。 ### 比較集合與陣列的使用 | 比較 | 集合 | 陣列 | | -------- | -------- | -------- | | 空間大小 | 不必指定大小,隨存入與移除元素動態伸縮、調整 | 必須指定長度,或在初次存放元素時固定長度 | | 資料類型 | 可以存放任何型別的物件作為元素,搭配泛型可限制存入元素型別| 可以存放物件或基本型別,但必須符合陣列宣告的資料類型 | | 資料取出 | for(無序集合不可使用)、for-each(無序集合不可使用)、Iterator | for、for-each| 再補充一個方便的特性:集合類別的 `toString()` 方法都有改寫,可以直接印出整個集合,方便觀察。可參考: 1. https://www.baeldung.com/java-list-to-string 2. https://stackoverflow.com/questions/395401/printing-java-collections-nicely-tostring-doesnt-return-pretty-output ### 集合相關的API架構圖 下圖最後更新日期:2021/03/15。 ![](https://i.imgur.com/Dg1nhlS.png) 1. 灰框代表介面,藍框代表該類別實作前述介面 3. LinkedList 同時實作 List、Queue 4. Vector 為 Thread-safe 的集合類別,方法使用和 ArrayList 相同 5. HashMap 另有相同使用方法的 Thread-safe 的集合類別 Hashtable ### Collection 介面、Map 介面 Collection 是存放**單一獨立物件**的集合的根介面;Map 相關的集合則必須持有**成對的物件 key 與 value**,是一種特別的集合;且 Collection Map 兩者並沒有繼承或實作的關係。 兩者都是介面,代表其中的方法都是抽象方法,實作其的類別、實作其子介面的類別都會繼承並實作它們的抽象方法,且各有其他功能特色,我們可以直接使用類別實作的方法。 ## Collection 介面與其子介面 實作 Collection 及其子介面的集合類別,其物件元素是各自獨立的物件。 ### 常用方法 * `boolean add(E obj)`:Collection 將物件加入陣列的方法。E代表參數型別可受泛型限制。回傳的 boolean 代表物件是否加入成功。 * `int size()`:集合的大小,注意**並不是** `length()`。 * `void clear`:淨空集合。 * `boolean isEmpty()` * `boolean remove(Object ojb)`:移除指定元素。 * `boolean contains(Object obj)`:是否包含指定元素。 * `Iterator iterator()`:取得迭代器走訪集合內所有元素。 * `Object[] toArray()`:將集合轉為陣列。 ### Collection 下子介面的比較 | 比較 | Set | List | Queue| | -------- | -------- | -------- |------ | | 順序 | 不保證順序(≠ 保證無序),僅有TreeSet保證順序(預設為大小順序)| 保證特定順序(預設為存入順序) | 保證特定順序(預設為大小順序)| |重複| 不允許重複(依序檢證 `HashCode()` 及 `equals()`)| 允許重複 | 允許重複 | |存取| 全元素只能以迭代器走訪取出,僅TreeSet可額外存取指定索引值 | 全元素可以迭代器、for-each、for走訪取出,且存取可指定索引值 | 僅能對第一個元素做取出,同時移除該元素(佇列的消化特性,適合FIFO的情況)| |實作| HashSet(無序)、TreeSet(有序)|ArrayList、Vector(含類別 Stack)、LinkedList|LinkedList、PriorityQueue| * FILO 情況用 Stack 集合類別取出並移除,但並不是透過 `remove()` 移除元素,而是[使用其方法](https://hackmd.io/yw4fpI5XTum6Pez0KrZ_Vw#stackpop) `pop()` ## Map 介面與其子類別 實作 Map 的集合類別 HashMap,其物件元素是成對的物件「主鍵值(key)」、「內含值(value)」。 * key:唯一性、不重複的資料。 * value:對應 key 的資料。 例如:座號、姓名。 ### 常用方法 * `Object put(Object key, Object value)`:將指定的值放入Map裡,Key、Map 相對。回傳值請見[注意事項](#ntc1)。 * `Object get(Object key)`:依指定的鍵,取得對應的值。==<font color=red>**並沒有依值找鍵的方法**</font>==。 * `void clear()` * `boolean containsKey(Object key)`:檢查 Map 內是否包含指定的鍵。 * `boolean cotainsValue(Object key)`:檢查 Map 內是否有指定的值。 * `int size()`:Map 的 key-value 總組數。 * `Set keySet()`:將 Map 內的所有鍵轉存成 Set 集合。為何存成 Set 請見[注意事項](#ntc2)。 * `Collection values()`:將 Map 內的所有鍵轉存成 Collection 集合。為何存成 Collection 請見[注意事項](#ntc3)。 ### 注意事項 #### <div id="ntc1">`Object put(Object key, Object value)` 的回傳值</div> 相同的主鍵值,舊資料會取代新資料,「重複即取代」的特性和 Set 的「重複不存入」並不相同。回傳值也並不是 boolean,若對映的 key 並無重複,成功存入將回傳 null 值;若相同 key 值重複存入,將回傳 key 存入的上一筆 value 值。 ```java= Map map = new HashMap(); map.put(1, "AAA"); map.put(2, "BBB"); map.put(3, "CCC"); map.put(3, "DDD"); // 將取代key值同為3的 CCC ``` #### <div id="ntc2">`Set keySet()` 為何將所有 key 值存成 Set 型別</div> key 要求不重複,很適合存在 Set(Set 中有無序的 HashSet 和有序的 TreeSet)。 #### <div id="ntc3">`Collection values()` 為何將所有 value 值存成 Collection 型別</div> value 沒有要求不重複,用 Set 來存不恰當(不然重複就不會存入);HashMap 物件本身沒有順序性,用 List 來存它的值也並不適合;所以選擇 Collection 介面作為型別。 ## 迭代器(Iterator) 將集合內的元素一個一個走訪、遍歷的行為稱之為迭代,Iterator 則是幫助我們達成該行為的工具(JDK 1.0時是Enumeration〈列舉〉介面在做的事)。 ### 方法 * `public boolean hasNext()`:這裡是否還有沒取過的元素,有就回傳true。 * `public Object next()`:取得元素。 ### 操作示範 以Set集合的走訪作為示範: ```java= Set set = new HashSet(); Iterator itSet = set.iterator(); // 宣告一個迭代器物件itSet // 呼叫Set物件set繼承自Collection的方法iterator() // 該方法將回傳一個專屬於set的iterator物件,指定給迭代器itSet設定 while(itSet.hasNext()){ System.out.println(itSet.next()); } ``` ## for-each 迴圈 可視為增強型的 for 迴圈(Enhanced for Loop),可以用於陣列或集合,且無須知道陣列或集合的長度即可對其內的元素展開走訪,但其走訪仍然**有順序性,所以 <font color=red>Set(HashSet)無法使用**</font>。 ### 實作 Iterable 介面的類別皆可以使用 Iterable 介面中只有 `Iterable<T> iterator()` 方法,回傳一個Iterable 介面,並可以使用泛型,和 Collection 介面的方法`Iterator iterator()` 有所不同。 ### 語法 ```java for (Type varName : listName) ``` * `Type varName`:宣告一個變數用來暫存從陣列或集合中取得的元素。 * `listName`:要走訪的有序集合,**必須實作Iterable介面,<font color=red>Map相關集合沒有實作,無法「直接」使用 for-each**</font>([如後述](#Map集合使用for-each走訪key值、value值))。 ### 操作示範 #### 有序集合使用for-each走訪 以List集合的走訪為例: ```java= List list = new List(); // 存有各式Object型別的物件 for (Object obj : list) { System.out.println(obj); } ``` #### Map集合使用for-each走訪key值、value值 前面講到Map相關集合因為沒有實作Iterable介面而無法直接使用for-each,但可以搭配: * `keySet()` 方法:將所有key轉存為Set型別的集合回傳。 * `values()` 方法:將所有value轉存為Collection型別的集合回傳。 因此還是可以使用 for-each 迴圈,因為 Collection 介面繼承了 Iterable 介面,而 Set 介面繼承了 Collection 介面,宣告為兩個型別的集合都 is an Iterable,其中存取的元素都 is an Object。 ```java=4 // 前略... Map map = new HashMap(); map.put("1", "星期一"); map.put("2", "星期二"); map.put("3", "星期三"); map.put("4", "星期四"); map.put("5", "星期五"); map.put("6", "星期六"); map.put("7", "星期日"); Set set = map.keySet(); // Set之中也包含有序的SortedSet:TreeSet,僅有HashMap集合只能使用迭代器走訪 Collection col = map.values(); System.out.println("===== 使用 keySet() 搭配 for-each 走訪 key 值====="); for (Object key : set) { // ↓ 等同 key.toString() System.out.println(key + "\t" + map.get(key)); // for-each 走訪存成 Set 物件 set 的所有 key 值 // value 則依然透過 HashMap 物件的 get() } System.out.println("===== 使用 values() 搭配 for-each 走訪 valus 值 ====="); for (Object value : col) { System.out.println(value); // for-each 走訪存成 Set 物件 set 的所有 key 值 // HashMap 或 Set 中都沒有方法可以直接獲得單獨的 key 值 } ``` 除了以上取出方法外,也可以參考以下幾個頁面,提供了很多意想不到但非常實用的取出方式: 1. [[JAVA]取出Map的資料使用loop -- Iterator、foreach、for](https://pclevinblog.pixnet.net/blog/post/314562493) 2. [Java Map集合的詳解](https://www.itread01.com/content/1550404270.html) 3. [什麼是Map集合?如何遍歷Map?](https://www.mdeditor.tw/pl/pTAo/zh-tw)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully