Kate Lo
    • 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
    # Week 6 ## Java: Generics - **Generics** enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. - A *generic* `Box` class allows you to define what type of elements will be put in the Box. For example, you can instantiate a `Box` object to keep `Integer` elements so that any attempt to put a non-`Integer` object in that `Box` object will result in a compile error. - **The definition of a generic class includes a type parameter section, delimited by angle brackets (<>).** It specifies the type parameters (also called type variables) T1, T2, ..., and Tn. A generic class is defined with the following format: ```java= class name<T1, T2, ..., Tn> { /* ... */ } ``` ![](https://i.imgur.com/rqrtiR2.png) - **To reference the generic `Box` class from within your code, you must perform a generic type invocation, which replaces `T` with some concrete value**, such as Integer. It is similar to an ordinary method invocation, but instead of passing an argument to a method, you are passing a type argument enclosed within angle brackets — e.g., <Integer> or <String, Integer> — to the generic class itself. Note that in some cases you can omit the type parameter i.e., <> if the type parameter can be inferred from the context. ![](https://i.imgur.com/0Ttzyyt.png) - The compiler is able to check for **type errors** when using generic code. - A generic class can have** multiple type parameters**. ![](https://i.imgur.com/dfOVAMk.png) - **A type variable can be any non-primitive type you specify**: any class type, any interface type, any array type, or even another type variable. - By convention, **type parameter names are single, uppercase letters**. ## Java: Collections - **A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit.** Collections are used to store, retrieve, manipulate, and communicate aggregate data. - The collections framework: - **Interfaces**: These are **abstract data types** that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. - Example: the `List<E>` interface can be used to manipulate list-like collections which may be implemented in different ways such as `ArrayList<E>` or `LinkedList<E>`. - **Implementations**: These are the **concrete implementations of the collection interfaces**. In essence, they are reusable data structures. - Example: the `ArrayList<E>` class implements the `List<E>` interface while the `HashMap<K, V>` class implements the `Map<K, V>` interface. - **Algorithms**: These are the methods that **perform useful computations**, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be **polymorphic**: that is, the same method can be used on many different implementations of the appropriate collection interface. - Example: the `sort(List<E>)` method can sort a collection that implements the `List<E>` interface. - **Core collection interfaces**: - ***Collection*** — the **root of the collection hierarchy**. **A collection represents a group of objects known as its elements.** The Collection interface is the least common denominator that all collections implement and is used to pass collections around and to manipulate them when maximum generality is desired. Some types of collections allow duplicate elements, and others do not. Some are ordered and others are unordered. The Java platform doesn't provide any direct implementations of this interface but provides implementations of more specific subinterfaces, such as Set and List. Also see the Collection API. - ***Set*** — **a collection that cannot contain duplicate elements**. This interface models the mathematical set abstraction and is used to represent sets, such as the cards comprising a poker hand, the courses making up a student's schedule, or the processes running on a machine. Also see the Set API. - ***List*** — **an ordered collection** (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position). Also see the List API. - ***Queue*** — **a collection used to hold multiple elements prior to processing**. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations. Also see the Queue API. - ***Map*** — **an object that maps keys to values**. A Map cannot contain duplicate keys; each key can map to at most one value. Also see the Map API. - Others: ***Deque***, ***SortedSet***, ***SortedMap*** ### **The `ArrayList` Class:** - The `ArrayList` class is a **resizable-array** implementation of the `List` interface. ```java= import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { ArrayList<String> items = new ArrayList<>(); System.out.println("Before adding any items:" + items); items.add("Apple"); items.add("Box"); items.add("Cup"); items.add("Dart"); print("After adding four items: " + items); items.remove("Box"); // remove item "Box" print("After removing Box: " + items); items.add(1, "Banana"); // add "Banana" at index 1 print("After adding Banana: " + items); items.add("Egg"); // add "Egg", will be added to the end items.add("Cup"); // add another "Cup" print("After adding Egg: " + items); print("Number of items: " + items.size()); print("Index of Cup: " + items.indexOf("Cup")); print("Index of Zebra: " + items.indexOf("Zebra")); print("Item at index 3 is: " + items.get(2)); print("Do we have a Box?: " + items.contains("Box")); print("Do we have an Apple?: " + items.contains("Apple")); items.clear(); print("After clearing: " + items); } private static void print(String text) { System.out.println(text); } } ``` -> ``` Before adding any items:[] After adding four items: [Apple, Box, Cup, Dart] After removing Box: [Apple, Cup, Dart] After adding Banana: [Apple, Banana, Cup, Dart] After adding Egg: [Apple, Banana, Cup, Dart, Egg, Cup] Number of items: 6 Index of Cup: 2 Index of Zebra: -1 Item at index 3 is: Cup Do we have a Box?: false Do we have an Apple?: true After clearing: [] ``` ### The `HashMap` Class: - `HashMap` is an implementation of the `Map` interface. It allows you to **store a collection of key-value pairs**. ```java= import java.awt.Point; import java.util.HashMap; import java.util.Map; public class HashMapDemo { public static void main(String[] args) { HashMap<String, Point> points = new HashMap<>(); // put the key-value pairs in the HashMap points.put("x1", new Point(0, 0)); points.put("x2", new Point(0, 5)); points.put("x3", new Point(5, 5)); points.put("x4", new Point(5, 0)); // retrieve a value for a key using the get method print("Coordinates of x1: " + pointAsString(points.get("x1"))); // check if a key or a value exists print("Key x1 exists? " + points.containsKey("x1")); print("Key y1 exists? " + points.containsKey("y1")); print("Value (0,0) exists? " + points.containsValue(new Point(0, 0))); print("Value (1,2) exists? " + points.containsValue(new Point(1, 2))); // update the value of a key to a new value points.put("x1", new Point(-1,-1)); // iterate over the entries for (Map.Entry<String, Point> entry : points.entrySet()) { print(entry.getKey() + " = " + pointAsString(entry.getValue())); } print("Number of keys: " + points.size()); points.clear(); print("Number of keys after clearing: " + points.size()); } public static String pointAsString(Point p) { return "[" + p.x + "," + p.y + "]"; } public static void print(String s) { System.out.println(s); } } ``` -> ``` Coordinates of x1: [0,0] Key x1 exists? true Key x1 exists? false Value (0,0) exists? true Value (1,2) exists? false x1 = [-1,-1] x2 = [0,5] x3 = [5,5] x4 = [5,0] Number of keys: 4 Number of keys after clearing: 0 ``` ## Java: File Access - **You can use the `java.io.File` class to represent a file object.** It can be used to access properties of the file object. ```java= import java.io.File; public class FileClassDemo { public static void main(String[] args) { File f = new File("data/fruits.txt"); System.out.println("full path: " + f.getAbsolutePath()); System.out.println("file exists?: " + f.exists()); System.out.println("is Directory?: " + f.isDirectory()); } } ``` -> ``` full path: C:\sample-code\data\fruits.txt file exists?: true is Directory?: false ``` - **You can read from a file using a `Scanner` object that uses a File object as the source of data.** ```java= import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class FileReadingDemo { private static void printFileContents(String filePath) throws FileNotFoundException { File f = new File(filePath); // create a File for the given file path Scanner s = new Scanner(f); // create a Scanner using the File as the source while (s.hasNext()) { System.out.println(s.nextLine()); } } public static void main(String[] args) { try { printFileContents("data/fruits.txt"); } catch (FileNotFoundException e) { System.out.println("File not found"); } } } ``` -> ``` 5 Apples 3 Bananas 6 Cherries ``` - **You can use a `java.io.FileWriter` object to write to a file.** ```java= import java.io.FileWriter; import java.io.IOException; public class FileWritingDemo { private static void writeToFile(String filePath, String textToAdd) throws IOException { FileWriter fw = new FileWriter(filePath); fw.write(textToAdd); fw.close(); } public static void main(String[] args) { String file2 = "temp/lines.txt"; try { writeToFile(file2, "first line" + System.lineSeparator() + "second line"); } catch (IOException e) { System.out.println("Something went wrong: " + e.getMessage()); } } } ``` -> ``` first line second line ``` - **You can create a `FileWriter` object that appends to the file** (instead of overwriting the current content) by specifying an additional boolean parameter to the constructor. ```java= private static void appendToFile(String filePath, String textToAppend) throws IOException { FileWriter fw = new FileWriter(filePath, true); // create a FileWriter in append mode fw.write(textToAppend); fw.close(); } ``` - The `java.nio.file.Files` is a utility class that provides several useful file operations. **It relies on the `java.nio.file.Paths` file to generate Path objects that represent file paths.** ```java= import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesClassDemo { public static void main(String[] args) throws IOException{ Files.copy(Paths.get("data/fruits.txt"), Paths.get("temp/fruits2.txt")); Files.delete(Paths.get("temp/fruits2.txt")); } } ``` ## Java: JAR Files - **Java applications are typically delivered as JAR (short for Java Archive) files.** **A JAR contains Java classes and other resources (icons, media files, etc.).** - An executable JAR file can be launched using the java -jar command. ## Requirements: Intro - **A software requirement specifies a need to be fulfilled by the software product.** - A software project may be, 1. **a brown-field project** i.e., develop a product to *replace/update an existing* software product 2. **a green-field project** i.e., develop a totally *new system* with no precedent - **Requirements come from stakeholders.** (A party that is potentially affected by the software project. e.g. users, sponsors, developers, interest groups, government agencies, etc.) - Requirements can be divided into two in the following way: 1. **Functional** requirements specify ***what the system should do***. 2. **Non-functional** requirements specify the ***constraints*** under which system is developed and operated. - **Product survey**: Studying existing products can unearth shortcomings of existing solutions that can be addressed by a new product. - **Observing** users in their natural work environment can uncover product requirements. - Surveys can be used to solicit responses and opinions from a large number of stakeholders regarding a current product or a new product. - **Prototype**: A prototype is a *mock up, a scaled down version, or a partial system constructed* - to get users’ feedback. - to validate a technical concept (a "proof-of-concept" prototype). - to give a preview of what is to come, or to compare multiple alternatives on a small scale before committing fully to one alternative. - for early field-testing under controlled conditions. - **Prototyping can uncover requirements, in particular, those related to how users interact with the system.** ## Requirements: Specifying - **A textual description (i.e. prose) can be used to describe requirements.** Prose is especially useful when describing abstract ideas such as the vision of a product. - **Use Case**: A description of **a set of sequences of actions, including variants**, that a system performs to yield an observable result of value to an actor - **A use case describes an interaction between the user and the system for a specific functionality of the system.** - **UML includes a diagram type called use case diagrams that can illustrate use cases of a system visually**, providing a visual ‘table of contents’ of the use cases of a system. - **Use cases capture the functional requirements of a system.** - **Glossary**: A glossary serves to ensure that all stakeholders have a common understanding of the noteworthy terms, abbreviations, acronyms etc. - A supplementary requirements section can be used to capture requirements that do not fit elsewhere. ## IDEs: Intermediate Features - **Debugging is the process of discovering defects in the program.**

    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