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> ::: # 模組19 集合物件唯一性(hashCode()、equals()) Set 集合相關的類別,雖然在順序性上並不是所有類別都能保證,但可以確定的是它們全都有**保證不重複**(唯一)的特性: * Set(不保證順序) * SortedSet(介面) * **TreeSet**(保證順序) * HashSet(不保證順序) * **LinkedHashSet**(保證順序,依加入先後) ## Set 相關集合判斷元素不重複的依據 **繼承自 Object** 的 2 個方法,能讓 Set 集合比對「準備存入的元素,是否和已經存在集合內的元素」重複: 1. `hashCode()`:模糊比對 2. `equals()` :明確比對 :::warning :mega: <font color="red">**比對絕對會依照此先後順序!**</font> `hashCode()` 若**相同**,才會再用 `equals()` 檢驗。一開始就用 `equals()` 太消耗資源了。 ::: Object 的 `equals()` 方法,為了讓所有物件都可以適用,只簡單的比較位址是否相同(`==`)的條件,因為位址相同的兩個物件必然相同。 但位址不同的物件,無法單就這個條件判斷是否重複,所以必須 Override 掉這兩個方法,才能定義什麼叫做「重複的物件」。 ## 模糊比對:`hashCode()` 雜湊碼比較 每個 Java **物件**都擁有繼承自 Object 的 `HashCode()` 方法,可以藉由它取得一個整數的資料。 基本型別就用它們自己的值,和一個質數一起做乘法運算:數字相關的型別用數值,char 用 unicode 的 byte 值、boolean 是 1 與 0。API 已有的單一物件類別通常已經也已經幫你 override 好,如 String 類別。 有多個屬性的物件,則通常必須拿每個屬性的 `hashCode()` ,和一個質數一起做累積的相乘,以避免因為乘出公倍數的關係得到相同的結果(共用雜湊桶,後述);做乘法運算的原因則是讓數字變大(不然桶子太少了很可能重複裝到)。 ### 雜湊桶(Hash Bucket) Java 在將集合加入元素前,就會呼叫這個預計要加入的物件的 `hashCode()` 方法,取得該物件運算完的整數資料。 這個整數資料,可以找到一個對應編號的雜湊桶(Hash Bucket): 1. **如果雜湊桶裡面是空的**:代表前面沒有物件和打算加入物件的屬性是相同的,這時候就可以直接加入這個集合,不需要再去呼叫 `equals()` 方法做明確比對。 2. **如果雜湊桶裡面已經有物件**:Java 會進一步去呼叫 `equals()` 方法檢查裡面的物件和打算加入的物件完全相同,這樣就可以確定重複了,不允許存入。 理由其實很簡單: > 所有屬性相同 → 所有屬性的 `hashCode()` 相同 > → 所有屬性的 `hashCode()` 乘以質數後算出相同的整數資料 > → 才有可能通往同一個雜湊桶 ### 應該覆寫些什麼? 依照前面的敘述,`hashCode()` 就是在幫你檢查物件裡面的屬性是不是和別人完全一樣,找雜湊桶時,雜湊桶變多、不產生公倍數也需要考量。所以大致上流程如下: 1. **決定好要比較的物件屬性**: 要和Override `equals()` 方法的屬性相同;如果不多,全放就對了。 <div style="margin-bottom:16px;" title="保持間距用"></div> 2. **選擇一個質數,與選擇的屬性作累積相乘**: 擴大運算結果,雜湊桶變多了,就可以避免撞雜湊桶。 <div style="margin-bottom:16px;" title="保持間距用"></div> 3. **回傳累積相乘的結果**: 讓 Java 去檢查這個數值對應的雜湊桶裡面有沒有東西,決定要不要呼叫 `equals()`。 ### Override `hashCode()` 的範例 ```java=4 // 前略... @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + dest.hashCode(); result = prime * result + number; result = prime * result + (int)price; result = prime * result + start.hashCode(); result = prime * result + type.hashCode(); return result; } ``` 計算應該比逐一條件比對更加節能,所以先在模糊比對階段確定沒有重複,直接存進來,可省下不少比對的效能。 ## 明確比對:`equals()` 相等比較 但所有屬性相同的物件是不是同一個物件?不一定!假設我 new 出了兩個屬性完全一模一樣的物件,就是一樣的嗎?它們光位址就不一樣了啊! 所以才要靠 `equals()` 做進一步的檢測。 ### Override `equals()` 的範例 `equals()` 的覆寫應該就不用講那麼多,直接來就對了。 ```java=4 // 前略... @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj != null && getClass() == obj.getClass() ) { Train train = (Train) obj; if (this.number == train.number && this.type == train.type && this.start == train.start && this.dest == train.dest && this.price == train.price) return true; } return false; } ``` :::warning :mega: <font color="red">**強制轉型的理由**</font>: 1. **與 Object 設計方法有關**: * 為了讓所有物件都可以傳進來,參數才會是`Object obj`,override 必須和父類別完全一致,但不轉型又沒有比較基礎(先求進來,再求轉回原本型別)。 * Object 不支援泛型,沒有先限制型別這種事情。 2. 集合什麼物件都可以存,傳入當作參數的物件,來源可能不同。但在這邊先放了 if 做條件檢測,如果檢查出兩者類別相同,就可以放心的強制轉型,**使傳入參數從多型 Object 轉回原來的型別**。來源相同,比較才有意義(來源的類別不同就直接跳出去回傳 false 就好,類別不同哪可能是同個物件啦)。 ::: ## 參考資料 補充一些不錯的參考資料: 1. [Effective Java Item11 - 覆蓋equals時總要覆蓋hashCode](https://www.jyt0532.com/2018/06/23/always-override-hashcode-when-you-override-equals/) 2. [物件相等性](https://openhome.cc/Gossip/JavaEssence/ObjectEquality.html)

    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