Sungchunn
    • 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
    • Make a copy
    • 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 Make a copy 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
    ## Problem 1 1. Classes in the same project, but in a different package, can have the same class name. **Answer: True** 2. A single class can extend from many different classes (i.e. `class A extends B, C, D`). **Answer: False** 3. Every class has the class `Object` as a super-class. **Answer: True:** Every Class extends from `Object` Class. 4. A custom exception that is a subclass of `RuntimeException` is a checked exception. **Answer: False:** A custom exception that is a subclass of RuntimeException is considered an unchecked exception, not a checked exception. In Java, checked exceptions are those that are checked at compile time for being properly handled or declared in the method's throws clause, and they are direct subclasses of Exception but not subclasses of RuntimeException. Unchecked exceptions are subclasses of RuntimeException and are not required to be declared or handled explicitly. 5. The following code prints true: **Answer: False:** Reference type needs to use the `.equal()` comparator. ```code=java int[] a=new int[]{11, 12, 25, 37}; int[] b=new int[]{11, 12, 25, 37}; System.out.println(a==b); ``` ## Problem 2 ```java public interface Magic { void magic(); } public interface Attack { void attack(); } public class Carry implements Attack { String name; private int magicNum = 42; public Carry(String name) { this.name = name; System.out.println(name + "ready"); } public Carry() { this("Unknown"); System.out.println("Using default"); } public void attack() { System.out.println(name + ":attack!"); } public void heal(int n) { System.out.println(name+":is healing!); if (n>0) throw new RuntimeException("cant"); System.out.println("Done!"); } } public class Valhein extends Carry implements Attack, Magic { public Valhein(String name) { super(name); System.out.println(name + ":choose a Valhein"); } public Valhein() { this("Unnamed Valhein"); } @Override public void magic() { System.out.println(name + ":use magic!"); } } ``` The Moba class below uses what we’ve just defined. For each line or group of lines of code (#1 through #10), indicate what will be printed. If it causes an error, explain what is wrong with the code. ```java public class Moba { public static void stageAttack(Attack o) { o.attack(); } public static void stageMagic(Magic o) { o.magic(); } public static void main(String[] args) { Valhein v = new Valhein("Peter"); // #1 Carry c = new Carry(); // #2 stageAttack(v); // #3 stageAttack(c); // #4 v.magic(); // #5 stageMagic(c); // #6 stageMagic(v); // #7 System.out.println(v.name); // #8 System.out.println(c.magicNum);// #9 Error // #10 begins -- try { c.heal(3); } catch (RuntimeException e) { System.out.println("Fail to heal"); } finally { System.out.println("Skill is Cooling down"); } // #10 } } ``` #### Answer: 1. `Peterready` `Peter:choose a Valhein` 2. `Unknownready` `Using default` 3. `Peter :Attack!` 4. `Unknown :Attack!` 5. `Peter : use Magic` 6. `Error` 7. `Peter : use Magic` 8. `Peter` 9. `Error` 10. `Unknown:is healing!` `Fail to heal` `Skill is Cooling down` ## Problem 3 fill in the blanks Below is a code snippet of a “view” class, whose constructor takes as input an array. The class itself supports “for-each” where all odd-indexed items (i.e., items in the arrays at indices 1, 3, 5, . . . ) are iterated over in turn. An example at the end shows how the class is used and its intended behavior. The relevant interfaces are `Iterator<E>` and `Iterable<E>`, where `Iterable<E>` expects an implementation of one method iterator, and `Iterator<E>` expects an implementation of two methods hasNext and next. Complete the code below by filling in the blanks. ```java import java.util.Iterator; import java.util.NoSuchElementException; public class OddIndexView<T> ____1____ { private ___2___ array; private class OddIndexViewer ____3____ { int curIndex; public OddIndexViewIter() { curIndex = ___4___; } public boolean hasNext() { ______5_____; } public T next() { // if there is a next item to return, return it // otherwise raise an exception NoSuchElementException if (___6___) { T retVal = ___7___; ___8___; // update curIndex return retVal; } else __________9______________; } public OddIndexView(T[] array) { this.array = array; } public Iterator<T> iterator() { return ________________10_________________ ; } } // sample main OddIndexView<String> view = new OddIndexView<>(new String[]{"ze", "ne", "wo", "ee", "hi"}); for (String st: view) { System.out.println(st); // would print ne and ee on separate lines } } ``` #### ANSWER: ```java import java.util.Iterator; import java.util.NoSuchElementException; public class OddIndexView<T> implements Iterable<T> { // Iterable<E> expects an implementation of one method iterator private T[] array; private class OddIndexViewer implements Iterator<T>{ // Iterator<E> expects an implementation of two methods hasNext and next. int curIndex; // typo issue? !OddIndexViewIter() public OddIndexViewer() { curIndex = 1; } public boolean hasNext() { return array.length > curIndex; } public T next() { // if there is a next item to return, return it // otherwise raise an exception NoSuchElementException if (hasNext()) { T retVal = array[curIndex]; curIndex += 2; // update curIndex return retVal; } else throw new NoSuchElementException("message"); } } public OddIndexView(T[] array) { this.array = array; } public Iterator<T> iterator() { return new OddIndexViewer(); } // array.next(); // simple main public static void main(String[] args) { OddIndexView<String> view = new OddIndexView<>(new String[]{"ze", "ne", "wo", "ee", "hi"}); for (String st: view) { System.out.println(st); // would print ne and ee on separate lines } } } ``` ## Problem 4: My Array List (10 points) Below, `MyArrayList` implements a list using a fixed-size array, doubling the capacity every time it becomes full. Using this as a starter, implement the following methods: - `public int removeFirst()` removes the number at start of the list (i.e., index 0) and returns that number. Note that after successfully completing this operation, the size of the list should decrease by 1. If the list is empty, this method will throw `NoSuchElementException`. Don’t worry about resizing the array down. - `public boolean equals(Object o)` returns true if this list equals the list in the other object. More precisely, the lists are equal if - They have the same encryptCode (i.e., both null or store the same string value); and - The same number of elements (size), and for each index in the list, the element at that index in our list and the element at that index in the other list are the same. You may find the following lines useful: ```java if (other == null || this.getClass() != other.getClass()) return false; if (other == this) return true; ``` ```java public class MyArrayList { private int[] items; private String encryptCode; private int size; public MyArrayList() { items = new int[2]; size = 0; encryptCode = null; } private void grow(int newCapacity) { int[] newItems = new int[newCapacity]; System.arraycopy(items, 0, newItems, 0, size); items = newItems; } public void add(int value) { if (size == items.length) { grow(items.length * 2); } items[size] = value; size += 1; } public void setEncryptCode(String val){ this.encryptCode = val; } public int size() { return size; } } ``` ### Answer: ```java public int removeFirst() { // If the list is empty, this method will throw NoSuchElementException if (size==0) { throw new NoSuchElementException("no such element") } else if (size==1) { System.arraycopy(items, 1, items, 0, size); size -= 1; return null; } else { System.arraycopy(items, 1, items, 0, size); size -= 1; return items[0]; } } ``` ```java // From ChatGPT // They have the same encryptCode (i.e., both null or store the same string value); and // The same number of elements (size), and for each index in the list, the element at that index in our list and the element at that index in the other list are the same. @Override public boolean equals(Object o) { // Check if the object is a reference to this instance if (o == this) return true; // Check if o is an instance of MyArrayList and not null if (o == null || getClass() != o.getClass()) return false; // Cast the Object to MyArrayList MyArrayList other = (MyArrayList) o; // Check if encryptCodes are both null or equal boolean encryptCodeMatch = (encryptCode == null && other.encryptCode == null) || (encryptCode != null && encryptCode.equals(other.encryptCode)); // If encryptCodes don't match, return false if (!encryptCodeMatch) return false; // Check if sizes are equal if (size != other.size) return false; // Compare each element in the array for (int i = 0; i < size; i++) { if (items[i] != other.items[i]) { return false; // If any element doesn't match, return false } } // If all checks pass, the objects are considered equal return true; } ```

    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