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
    • 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 Versions and GitHub Sync Note Insights 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    :::info <a href="/@TFA101/CherryJava" target="_self">< :notebook_with_decorative_cover: [共享目錄] Java 2 學習筆記 </a> ::: # 模組18 集合物件排序(Comparable、compareTo()、sort()) 集合中,有順序性的集合如下: * List(存在我底下的絕對保證順序) * **ArrayList** * **Vector** * **LinkedList**(Queue 再來說明) * Set(我只保證不重複,不要以為存在我底下的就不保證順序!) * SortedSet(介面) * **TreeSet**(同時具備不重複、有順序的特性;單值獨立存取) * HashSet(我不保證順序) * **LinkedHashSet**(我有順序性,依照加入先後為順序) * Map(我保證 key 值重複就覆蓋舊的 value 值) * **TreeMap**(同時具備重複就覆蓋、有順序的特性;對映存取,依 key 值排序) * HashMap(我不保證順序) * **LinkedHashMap**(我有順序性,依照加入先後為順序) * Queue(有順序性、消化性) * **LinkedList** * **PriorityQueue** ## 集合排序元素的依據 這些集合的排序以下列介面及其抽象方法為依據: * 介面:Comparable<T> * 抽象方法:`compareTo(T target)` ### 實作 Comparable 介面 想藉由陣列或集合擁有大小排序的特性,必須主動實作 Comparable 介面,再依自訂的大小定義和排序規則去 Override 掉(實作)它的抽象方法 `compareTo()`。 :::warning 記得 [Comparable 可以宣告泛型](https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html),如: `Class Test implements Compareble<Example>`。 不宣告泛型可不可以?可以。 但此時則會以 `Obejct` 為型別,`compareTo(Object obj)` 方法傳入的參數就會是 `Object` 型別。進行排序前要先強制轉型,存為用來呼叫此方法的物件的型別(比較大小的兩者要同源才有意義)。 ::: ### Override `compareTo(T target)` 方法 :::warning 下面範例中,傳入的參數 `Example ex` 的型別 `Example` 即是在實作 Comaparable 介面時就已宣告的泛型,這樣在比較時就不需先強制轉型,當然也不用先檢查它的型別。 ::: ```java= // 前略... // 假設已於實作Comaparable時宣告泛型<Example> // 某集合存放的Example物件,有number屬性,在compareTo設定為排序依據 public int compareTo(Example ex) { if(this.number > ex.number) return 1; else if(this.number == ex.number) return 0; else return -1; } ``` 排序將會依 `public int compareTo(T target)` 的回傳值,來排定元素的順序: :::warning 呼叫這個方法的是集合(或準備加入集合)內的元素,傳進來的參數也是集合(或準備加入集合)內的元素。 ::: 1. **回傳值是 ==大於 0== 的整數(例子中為 `1`)時**: 用來呼叫的物件存到參數傳入的物件的 ==右邊==。 <div style="margin-bottom:16px;" title="保持間距用"></div> 2. **回傳值 ==正好為0== 時**: 用來呼叫和傳入參數的物件沒有大小之分,只要兩個人左右存在一起就好。 <font color=red>但在可排序、保證不重複的 TreeSet 中,回傳值為 `0` 會是不重複的根據,後來的物件將會不被允許加入。</font> <div style="margin-bottom:16px;" title="保持間距用"></div> 3. **回傳值是 ==小於 0== 的整數(例子中為 `-1`)時**: 用來呼叫的物件存到參數傳入的物件的 ==左邊==。 ### if 條件與 compareTo() 的回傳值 須注意,回傳值需要搭配 `if` 的條件判斷。此範例中回傳 `1` 的條件為 `this.number > ex.number`,因此將會由小至大排序。 反之,若在 `if (this.number < ex.number)` 時回傳 `1`,則代表「如果用來呼叫的物件比傳入參數 ex 的 number **<font style="text-decoration:underline">小</font>**,就移動到 **<font style="text-decoration:underline">右邊</font>**」,可以達到由大到小反向排序的效果。 :::info :bulb: <span style="border-bottom: 1px solid #31708f;">**Tip**</span> 如果用來比較的值**剛好都是整數的話**,若要由小至大排列,其實可以寫成這樣: <div style="margin-bottom:16px;" title="保持間距用"></div> ```java public int compareTo(Example ex) { return this.number - ex.number; } ``` 回傳值符合存入順序的條件。由大至小排列則可以寫成 `return ex.number - this.number;`。 ::: ## 自動排序 學習陣列(Array)相關的方法時,應該大家都記得某個 static 方法 `Arrays.sort()`,集合類別也有類似的方法 `Collections.sort()`。 :::warning [Array](https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Array.html) 類別 / [Array<font style="text-decoration:underline; font-weight:bold;">s</font>](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html) 類別,[Collection](https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html) 介面 / [Collection<font style="text-decoration:underline; font-weight:bold;">s</font>](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html) 類別,千萬要搞清楚。 ::: 當時我們只知道呼叫它,會依照自然順序,由小至大排列。 **其實這個所謂的「自然順序」就是由 `compareTo(T target)` 方法定義的**。陣列或集合物件傳入 `Arrays.sort()` 或 `Collections.sort()`,兩個方法內部會自動去呼叫該物件的 `compareTo(T target)`。 所以如果改變(Override)了該集合或陣列物件類別中 `compareTo(T target)` 方法的排序規則,會影響到物件呼叫與將物件傳入 `Arrays.sort()` 或 `Collections.sort()` 排序時,排出來的元素順序。

    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