Advanced Java: Collections, Generics and More
The Java you need beyond the basics: lists, stacks, queues, maps and sets, iterators, generics, ordering, equals and hashCode, enums, nested classes, immutability and resources. Every lesson traces a real program line by line.
The Collections Framework
- ArrayList: A Growable List: Add, insert, read, replace and remove items, and watch later items shift as the list changes.
- Stacks and Queues with ArrayDeque: One class, two behaviours: push/pop for last-in-first-out, offer/poll for first-in-first-out.
- HashMap: Look Up by Key: Store values under keys, replace them, read missing keys safely, and loop over every entry.
- Sets: HashSet and TreeSet: Collections with no duplicates. HashSet is fastest; TreeSet keeps items sorted.
- Iterators: Removing While Looping: Removing from a list inside a for-each loop crashes. An Iterator lets you remove the current item safely.
Generics
- Generic Classes: Write one Box class that can hold any type, while the compiler still checks you put in and take out the right kind of thing.
- Generic Methods, Bounds and Wildcards: One largest() method for any comparable type, and a sum() that accepts a list of any kind of number.
Ordering and Equality
- Comparable and Comparator: Give a class a natural order with compareTo, and sort it any other way with a Comparator.
- equals and hashCode: Why does a HashSet keep two "identical" objects? Because without equals and hashCode, Java only compares identity.
More Language Features
- Enums with Fields and Methods: An enum is a fixed set of named constants, and each constant can carry its own data and behaviour.
- Nested, Inner and Anonymous Classes: Classes inside classes: a static helper, an inner class tied to an outer object, and a one-off anonymous class.
- Immutable Classes and Defensive Copies: Make an object that can never change: final fields, copies in and out, and "with" methods that return new objects.
- try-with-resources and AutoCloseable: Open a resource in the try header and Java closes it for you at the end, even if something goes wrong.
- Varargs: Any Number of Arguments: int... lets a method accept zero, one or many arguments, which arrive as an array.