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

  1. ArrayList: A Growable List: Add, insert, read, replace and remove items, and watch later items shift as the list changes.
  2. Stacks and Queues with ArrayDeque: One class, two behaviours: push/pop for last-in-first-out, offer/poll for first-in-first-out.
  3. HashMap: Look Up by Key: Store values under keys, replace them, read missing keys safely, and loop over every entry.
  4. Sets: HashSet and TreeSet: Collections with no duplicates. HashSet is fastest; TreeSet keeps items sorted.
  5. Iterators: Removing While Looping: Removing from a list inside a for-each loop crashes. An Iterator lets you remove the current item safely.

Generics

  1. 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.
  2. 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

  1. Comparable and Comparator: Give a class a natural order with compareTo, and sort it any other way with a Comparator.
  2. equals and hashCode: Why does a HashSet keep two "identical" objects? Because without equals and hashCode, Java only compares identity.

More Language Features

  1. Enums with Fields and Methods: An enum is a fixed set of named constants, and each constant can carry its own data and behaviour.
  2. 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.
  3. 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.
  4. 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.
  5. Varargs: Any Number of Arguments: int... lets a method accept zero, one or many arguments, which arrive as an array.