UNC COMP 301 - F26/Lec 8 - Java Collections Framework - HashMap, HashSet; Error Handling
Watch on YouTube →
Overview
Muhammad Sayeed Ghani reviews Java Collections Framework interfaces and implementations—especially `Map`/`HashMap` and `Set`/`HashSet`—then applies Java exception handling to resource cleanup, checked exceptions, and custom exception types. The lecture connects hash-table concepts from COMP 210 to assignment 3 and works through `finally`, nested `try`/`catch`, and Java’s catch-or-specify compile-time rule.
Key takeaways
- `Map<String, String>` backed by `HashMap` is appropriate for key-to-value lookup; inserting an existing key replaces its value rather than creating a duplicate key.
- `HashSet` provides unique-element storage and, as explained in the lecture, is implemented using a backing `HashMap`; use `TreeSet` for sorted elements or `LinkedHashSet` to preserve insertion order.
- Closing a file only inside a `try` block is unsafe because an exception can skip the close and leave buffered output unwritten; placing cleanup in `finally` ensures it runs across normal and exceptional paths.
- Checked exceptions such as `FileNotFoundException` and `IOException` must be caught or declared with `throws`, and the Java compiler checks this rule at compile time.
- A custom exception’s superclass determines whether it is checked: extending `Exception` creates a checked exception, while extending `RuntimeException` creates an unchecked one.
Chapters
0:00
Assignment 3, Midterm Coverage, and the Java Collections Framework
- Assignment 3 was released the previous night, with a regular deadline about seven days away and an extended deadline after the midterm.
- Ghani introduces `HashMap`, `Map`, `HashSet`, and `Set` because these collections will be useful in assignment 3.
- Today’s and Thursday’s lectures are included in the midterm coverage; the following Tuesday’s lecture is excluded.
4:30
`Map<K,V>` and `HashMap`: Storing Key-Value Pairs
- The Java Collections Framework includes single-element collections such as `List` and `Set`, plus the separate `Map` interface for key-value pairs.
- The example declares a `Map<String, String>` reference backed by a `HashMap<String, String>`, illustrating programming to an interface.
- `put`, `get`, `remove`, `containsKey`, `containsValue`, `size`, `isEmpty`, and `clear` are introduced as common `Map` operations.
- Keys are unique: calling `put` with an existing key replaces its previous value.
7:29
`HashMap` Buckets, Hashing, and Collision Chaining
- A simplified `HashMap` model stores entries in an internal array of buckets; the example uses four buckets.
- A key’s hash is mapped to an array index with modulo: hash value 9 and capacity 4 produce index 1.
- When keys map to the same bucket, the lecture describes collision resolution through chains of key-value nodes rather than probing.
- Lookup is expected to take constant time with a well-sized table and short chains, although the worst case can be linear.
16:10
`TreeMap`, `LinkedHashMap`, and the `Set` Interface
- `TreeMap` maintains sorted keys using a red-black tree, while `LinkedHashMap` preserves insertion order.
- A regular `HashMap` does not promise sorted or insertion order; assignment 3 primarily uses `HashMap`.
- `Set<E>` stores unique elements, and `HashSet` ignores duplicate additions such as a second `Alice`.
- `HashSet` is presented as using a backing `HashMap` with a dummy value; `TreeSet` sorts elements and `LinkedHashSet` preserves insertion order.
21:30
Choosing Lists, Sets, Maps, Queues, and Deques
- A `List` preserves order and permits duplicates, making it suitable for logs or repeated bank transactions.
- A `Set` fits collections that require uniqueness, such as students enrolled in a class or unique users in a session.
- A `Map` supports fast lookups such as domain-name-to-IP-address resolution or user-ID-to-username mapping.
- Queues support FIFO scheduling, while stacks support LIFO behavior such as the program call stack; Java’s `Deque` can implement both.
25:00
Exception Hierarchy and the Problem with Skipped Cleanup
- The exception hierarchy places `Throwable` above `Exception` and `RuntimeException`; checked and unchecked categories are distinguished in the lecture’s diagram.
- In the file-writing example, the program divides 100 by each integer and encounters an `ArithmeticException` when an input is zero.
- Because `writer.close()` is inside the `try` block, an exception can bypass it and leave buffered output unwritten.
27:00
Using `finally` to Close Files After Exceptions
- A `finally` block runs after the `try`/`catch` flow, including when an exception is caught or propagates onward.
- The writer must be declared outside the `try` block so its variable remains in scope inside `finally`.
- With zero in the input array, the revised example closes the file and preserves the two successful division results written before the error.
31:50
Tracing `finally` with Caught Exceptions and Early Returns
- In the first poll, a runtime exception does not match a `NullPointerException` catch but does match a later `RuntimeException` catch.
- The output sequence includes the initial print, the matching catch, the `finally` print, and then subsequent code because the exception was caught.
- In the return example, `finally` prints `B` before the method returns; code after the `try` does not print `C`.
45:43
Nested `try`/`catch` and Exception Propagation Between Methods
- A null list causes a `NullPointerException` in the called method; an `ArithmeticException` catch does not match it.
- The called method’s `finally` prints `G`, then the uncaught exception returns to the caller.
- The caller catches the exception as a `RuntimeException`, prints `B`, runs its `finally` to print `D`, and continues with later code.
50:07
Nested Catch Blocks, Arithmetic Errors, and Output Order
- A null list first triggers a `NullPointerException`, which is caught by a `RuntimeException` handler.
- Inside that handler, division by zero triggers an `ArithmeticException`, which the nested catch handles and prints as `A`.
- The nested `finally` then prints `C`, and execution continues to print `D`; a later parallel catch is skipped once the exception is caught.
55:12
Checked Versus Unchecked Exceptions in Java
- The lecture characterizes unchecked exceptions such as `ArithmeticException` and `NullPointerException` as commonly indicating programming errors.
- Checked exceptions often represent conditions outside the program’s control, such as a missing file or unavailable network resource.
- Java requires checked exceptions to be caught or declared as thrown, enforcing explicit handling or propagation.
58:41
Handling `FileNotFoundException` with `try`/`catch` or `throws`
- Opening a file with `Scanner` can produce a checked `FileNotFoundException`, which the compiler flags if left unhandled.
- One solution wraps file access in `try`/`catch` and handles the exception with an error message or stack trace.
- The alternative adds `throws FileNotFoundException` to the method signature, requiring callers to catch the exception or declare it onward.
1:02:00
Catch-or-Specify, Compile-Time Checks, and Static Analysis
- If `methodOne()` declares `throws IOException`, its caller must catch the exception or add a `throws` declaration—even if the method body does not actually throw one.
- The compiler reports the unhandled checked exception at the call site; declaring `throws IOException` on `main` or catching it there resolves the issue.
- Catch-or-specify violations are compile-time errors found through static analysis, alongside checks such as unreachable code.
1:11:30
Creating a Checked Custom Exception: `ShortOfFunds`
- A banking example motivates a custom `ShortOfFunds` exception for withdrawals that exceed an account’s balance.
- Extending `Exception` makes `ShortOfFunds` checked, so callers must catch it or declare it; extending `RuntimeException` would make it unchecked.
- Ghani begins examining the custom exception class in IntelliJ but pauses the implementation walkthrough to continue in Thursday’s lecture.
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Muhammad Sayeed Ghani.