Tutorial 1: Collections, Exceptions, and Files

Unit 9 ยท Robust data-driven programs

Objectives

Use ArrayList for ordered, resizable data and HashMap for key-to-value lookup. Generics document the element type and prevent many casts.

List<String> topics = new ArrayList<>();
topics.add("classes");
topics.add("testing");
Map<String, Integer> minutes = new HashMap<>();
minutes.put("classes", 45);

try {
    List<String> lines = Files.readAllLines(Path.of("study.txt"));
    System.out.println(lines.size());
} catch (IOException error) {
    System.err.println("Could not read study file: " + error.getMessage());
}

Catch the narrowest exception you can handle. Never use an empty catch block. Preserve useful context in an error message or rethrow with a cause.

Practice

  1. Count word frequencies with a Map<String,Integer>.
  2. Load study topics from a file and ignore blank lines.
  3. Simulate a missing file and write a helpful recovery message.

Self-check

  1. When is a map better than a list?
  2. What does a checked IOException force you to do?
  3. Why is an empty catch dangerous?

Mastery task: Build a command-line study log that loads entries, adds a session, and saves the updated data.