The cost of not presizing collections
A model that follows the JDK's growth rules (Topics 9.2 and 9.4). Growth is amortised O(1), so this matters for very large or very frequently built collections, not for small ones. HashMap.newHashMap(n) (Java 19) does the load-factor arithmetic for you.
Most slow Java code is slow for a handful of ordinary reasons: the wrong algorithm or collection, needless allocation and boxing, string building in loops, exceptions and logging in hot paths, lock contention, and I/O done one byte or one query at a time. Measure first, fix the biggest cost, and measure again.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Rewrite a method that joins 1 to 10 with commas using += into one using StringJoiner, and print the result.
Given an array of 10 ints with duplicates, count distinct values using a HashSet instead of nested loops, and print the count.
Write a static final Pattern that matches product codes like ABC-1234, test it on three inputs, and print the results.
Explain it without notes
How do you approach a "the service is slow" report?
Why is s += x in a loop slow, and why is a + b + c not?
What are the costs of autoboxing, and how do you avoid them?
What is the N+1 query problem and how do you fix it?
Expected output
ArrayList, default: 29 grows, 2430972 elements copied
ArrayList, presized: 0 grows, 0 elements copied (new ArrayList<>(n))
HashMap, default: 17 resizes, 1572869 entries rehashed, table 2097152
HashMap, presized: capacity for 1000000 entries must be >= 1333334