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> ::: # 模組16 泛型(Generic) 常與集合(Collection)相關類別一起使用,Collection 天生沒有規定存放物件的型別(Object 都可以存入),泛型可用來<font color=red>**限制**</font>所含物件的類別。 ### Collection 的一般化 經過泛型限制型別後的 Collection,無法存放,失去了有容乃大、包山包海的特異功能……但泛型帶來的好處更多。 ### 泛型帶來的好處 * 不是泛型所指定的型別,在**編譯階段**就會出現錯誤 * 型別已知,取出資料時可省略型別轉換(Cast) * 不用檢查是否可以轉型 * 不會有機會發生 ClassCastException 的例外 * 使用動態連結技術 * 使集合以 Obejct 作最基本的多型 ## 泛型的格式 ### API 文件 類別後若標有一對角括號 `<>`,表示支援泛型。角括號內會有以下幾種表示方式: | 自訂泛型的對象 | 定義 | | ---------- | -------------- | | T(Type) | 限制資料的型別 | | K(Key) | 限制 Map 相關類別物件中存放的 key 值的型別 | | V(Value) | 限制 Map 相關類別物件中存放的 value 值的型別| | E(Element) | 限制陣列或集合物件中存放的元素(Element)的型別 | ### 基本的泛型 以 `Class ArrayList<E>` 為例,傳達 2 件與泛型相關的事實: 1. **1 個字母**:代表宣告了一個資料類型的泛型。 2. **字母是 E**:這個資料類型是指定給 ArrayList 的元素的限制。 另外 Map 相關介面與類別的泛型會是一對的(2個字母),分別指定給 key 值和 value 值,如 `HashMap<K, V>`。 ### 上下邊界的泛型 以下格式可以更進階的設定泛型的範圍(`?` 表示「any type」)。換句話說,不符合就不能指定進去: 1. `<? extends Example>`:在<>中指定的型別可以是 Example 的子類別。 2. `<? super Example>`:在<>中指定的型別可以是 Example 的父類別。 此機制可以確保使用者不會使用到無關的資料型別,通常用於: 1. <font color=red>**方法的參數**</font> 2. <font color=red>**回傳型別**</font> ## 使用語法及範例 :::warning 角括號 `<>` 內只能放類別,**基本型別需用對應的包裝類別**。 例如::o: `<Integer>`、:x: `<int>` 。 ::: 1. 在產生新的集合物件時,就會先指定該集合物件的泛型。 ```java=1 List list<String> = new ArrayList<String>(); ``` 2. 在存取物件、或想使用某型別才能使用的方法時,不需強制轉型。 ```java=2 // 前略... Iterator it = list.iterator(); while(it.hasNext()) { String str = it.next(); // 原本要寫成 String str = (String)it.next(); // 因為存取的物件可能不是 String,不能存入 str System.out.println(str); } ``` ```java=4 // list 集合物件中存放了某種物件 // 該物件會有3種不同型別的屬性、1種showInfo()方法可印出所有屬性 while(it.hasNext()) { it.next().showInfo(); // 就不用寫成 String str2 = (String)it.next(); } ``` ## 自訂泛型 以自己創建的類別作為泛型指定的型別。 1. **設定想作為泛型的類別**:其實<>內寫什麼都隨便你,使用的時候指定的泛型型別,會把這個字全部取代就對了。 ```java= Class MyGenericType { private List<Type> list; // 建構子:呼叫此建構子時將產生一個Vector物件,指定給 list public MyGenericType() { list = new Vector<Type>(); // 新的Vector物件也以泛型指定型別 } // 一般方法:add物件,也算是setter public void add(Type t) { // 傳入的參數以泛型指定型別 list.add(t); } // 一般方法:getter,依傳入參數作為索引值,取得元素 public Type get(int i){ // 回傳值也以泛型指定型別 return list.get(i); } ``` 3. **使用自訂泛型的類別**:範例中,所有類別中的 `<Type>` 泛型都被取代。 ```java= public class Test { public static void main(String[] arg) { MyGenericType<String> myGeneric = new MyGenericType<String>(); for(int i = 0; i < 3; i++){ myGeneric.add("number" + i); // set System.out.prtinln(myGeneric.get(i)); // get } } } ```

    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