UNC COMP 301 - F26/Lec 8 - Java Collections Framework - HashMap, HashSet; Error Handling
Overview
Muhammad Sayeed Ghani reviews Java Collections Framework structures needed for Assignment 3, focusing on the Map and Set interfaces, HashMap and HashSet, hash-table collisions, and collection use cases. He then explains Java exception control flow, resource cleanup with finally, checked versus unchecked exceptions, the catch-or-specify rule, compiler checks, and the start of defining a custom checked exception.
Key takeaways
- Use Map<K, V> as the declared type and HashMap<K, V> as the implementation when key-value lookup is needed; inserting an existing key replaces its value.
- HashMap uses bucket-based collision handling described here as chaining, giving expected O(1) lookup with short chains but a possible O(n) worst case.
- HashSet enforces uniqueness and is described as using a HashMap internally, while LinkedHashSet preserves insertion order and TreeSet keeps elements sorted.
- Put resource cleanup such as closing a file writer in finally, and declare the resource variable in a scope visible to that block.
- Java requires checked exceptions to be caught or declared with throws, and a caller that invokes a method declaring IOException must satisfy that rule even if no exception is actually thrown.
- A custom exception extending Exception is checked, while one extending RuntimeException is unchecked.
Chapters
- Assignment 3 was released, with a regular deadline about seven days after this lecture and an extended deadline after the midterm.
- The lecture connects Java collections to COMP 210 data structures, especially hash tables, and previews error handling.
- Only the current and Thursday lectures were identified as midterm material; the following Tuesday lecture was excluded.
- The Java Collections Framework in java.util includes List, Set, Queue, and Map interfaces and their implementations.
- List and Set are single-element collections, while Map stores key-value pairs and is not itself part of the Collection interface.
- Assignment 3 is expected to use the Set interface with HashSet and the Map interface with HashMap.
- The example declares a Map<String, String> reference backed by a new HashMap, demonstrating programming to an interface.
- Map methods include put, get, remove, containsKey, containsValue, size, isEmpty, and clear.
- Map keys are unique: calling put with an existing key, such as google.com, replaces its previous value.
- A HashMap object holds a reference to internal table storage, conceptually an array of buckets.
- The example hashes google.com to 9 and computes 9 modulo a table size of 4, selecting bucket index 1.
- A bucket entry represents a key-value pair, with a link to another entry when multiple keys map to the same bucket.
- The lecture contrasts probing methods such as linear probing, quadratic probing, and double hashing with chaining.
- HashMap is described using bucket chains, where a bucket points to a sequence of entries that must be checked for a matching key.
- Expected lookup is approximately O(1) with a reasonable table size and short chains; the worst case can be O(n).
- Resizing helps keep average chain lengths small, and the detailed hash-function implementation is treated as COMP 210 review rather than a COMP 301 exam focus.
- TreeMap keeps keys sorted using a red-black tree, while LinkedHashMap preserves insertion order; HashMap guarantees neither order.
- Set stores unique single elements, and HashSet ignores duplicate additions such as a second Alice.
- HashSet is presented as using a HashMap internally, with the map value serving as a dummy placeholder.
- List preserves order and allows duplicates, making it suitable for action logs or bank transactions.
- Set fits unique collections such as students in a class, active users, or hashtags; Map supports fast associations such as DNS names to IP addresses or user IDs to names.
- Queue models FIFO task scheduling, while a stack models LIFO behavior such as a program call stack.
- The lecture returns to exception handling, introducing the Throwable, Exception, and RuntimeException hierarchy.
- The example writes results of 100 divided by several integers to output1.txt and closes the writer inside the try block.
- When a zero denominator causes ArithmeticException, control jumps to a catch block before writer.close executes.
- Buffered output may remain unwritten, so even results calculated before the exception can be missing from the file.
- Moving writer.close into a finally block ensures cleanup after normal execution, a caught exception, or an uncaught exception in the try.
- The writer variable must be declared outside the try block so that the finally block can access it.
- With division by zero, the corrected example closes the file and retains the first two successful results.
- In the first control-flow poll, a RuntimeException skips a nonmatching NullPointerException catch and reaches the RuntimeException catch.
- The finally block prints E, and because the exception is caught, execution continues to print F.
- When a try block returns immediately, finally still runs first: the example prints B but does not reach later statement C.
- A null list causes NullPointerException, which does not match an ArithmeticException catch in the inner method.
- The inner finally prints G before the uncaught exception returns to the calling method.
- A caller's RuntimeException catch can catch NullPointerException, after which the caller's finally still runs.
- A second nested example catches NullPointerException, then catches division by zero as ArithmeticException, runs finally, and continues to later statements.
- RuntimeException subclasses such as ArithmeticException and NullPointerException are unchecked and are framed as likely programming bugs.
- Checked exceptions represent anticipated external failures, such as a missing file or an unavailable internet connection.
- Java requires checked exceptions to be caught or declared in a method's throws clause.
- Opening a file with Scanner can produce FileNotFoundException, which the compiler requires the code to handle.
- One option is a try-catch block that catches FileNotFoundException and reports or otherwise handles the failure.
- The alternative is to add throws FileNotFoundException to the method signature, passing responsibility to its caller.
- If method one declares throws IOException, a call to method one must be caught or declared by its caller, even if the method body never actually throws.
- The lecture's example identifies the call in main as the compile-time error because main neither catches IOException nor declares it.
- The issue can be resolved by wrapping the call in a try-catch block or adding a throws declaration to main.
- Java compilation checks syntax, unreachable code, and violations of the checked-exception catch-or-specify rule.
- Checked exceptions are compile-time obligations, but an exception that occurs during execution is still a runtime event.
- The broader Throwable hierarchy also includes serious Error conditions such as stack overflow and running out of memory.
- A custom ShortOfFunds exception is introduced for a banking example where a withdrawal exceeds the account balance.
- Extending Exception makes ShortOfFunds a checked exception; extending RuntimeException instead would make the custom exception unchecked.
- The lecture ends before completing the implementation, with the example scheduled to continue in the next lecture.
Transcript excerpt
0:01 Good afternoon everyone. So um assignment number three was released last night. I hope people have started taking a look at it. Um and while it's due the regular deadline is in about 7 days. However, the extended deadline will be after the midterm. So you will have some few extra days but I would recommend that you try to do it beforehand. Um now before we get on to where we were as far as error handling is concerned, I would like to spend some time introducing the Java collections framework which is sort of a throwback to uh some of the topics that we've discussed in data structures in 210. Uh basically hash maps uh we kind of
0:50 referenced it but we didn't really talk about it. map interface, the set interface and hash set implementation. And the reason why we're discussing that now is because uh that's something that's going to be coming in handy in assignment number three. And then we'll go back and continue where we left off on uh discussions on uh error handling. And um time permitting, we might start the next major topic today as well. I probably probably won't have much time for that which is um software testing and JUnit but let's start first of all with Java collections framework. Now before I forget uh I would like to mention that uh today and Thursday's lectures will be
1:39 the only lectures that will be covered as far as the end of the u the ending portion. So next Tuesday's uh lecture will not be covered in the midterm. Um there should be uh some sample questions coming out by the end of the week as well. All right. And we should have uh a tutorial a review session as well
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
In this course
Related notes
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.