Turning a hidden runtime bug into an early one with Collections.checkedList
Raw types let an Integer into a List<String>. A checked list catches it at the faulty add, which is where you want the stack trace.
Generics let a class or method work with many types while the compiler still checks which type you used. List<String> is a list the compiler knows holds only strings, so wrong elements become compile errors and the casts disappear.
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.
Write a program that stores three city names in a List<String>, then prints the total number of characters, without any casts.
Write a Map<String, Integer> word counter for the words {"tea", "chai", "tea", "coffee", "tea"}, using a TreeMap so the output order is fixed, and print the map.
Write a generic-free ObjectPair class holding two Objects, then a generic Pair<A, B>. Store ("Asha", 92) in each and print the name length and the mark plus 1, showing where casts are needed.
Explain it without notes
What problem did generics solve? Describe how the same bug behaves with and without them.
What is the difference between a type parameter and a type argument?
Why can't you write List<int>, and what happens when you add an int to a List<Integer>?
What is a raw type, why does Java still allow it, and why should you avoid it?
Expected output
plain list now holds: [99]
checkedList rejected the add
guarded list: []