
Your learning drop for cleaner APIs and safer code. Below are 7 field-tested habits (with tiny snippets) to make your generics rock.
TL;DR
- ▪️ Avoid raw types, kill unchecked warnings, and prefer List over arrays.
- ▪️ Make your types and methods generic to push errors to compile time.
- ▪️ Use bounded wildcards (? extends / ? super) to keep APIs flexible.
- ▪️ For advanced cases, typesafe heterogeneous containers give you compile-time safety without casts.
🔸 DON’T USE RAW TYPES IN NEW CODE
Always parameterize collections and generics—raw types drop type safety.
Why: Raw types bypass generics checking → casts, ClassCastException at runtime.
🔸 ELIMINATE UNCHECKED WARNINGS
Make the compiler happy—warnings often hide real type risks.
Tip: Prefer designs that avoid @SuppressWarnings; if used, document why it’s safe.
🔸 PREFER LISTS TO ARRAYS
Choose List
over T[]—because arrays are reified & covariant (checks at runtime), while generics are erased & invariant (checks at compile time).
Reason: Arrays are covariant + runtime checks; Lists are invariant + compile-time checks.
🔸 FAVOR GENERIC TYPES
Make your classes generic instead of storing Object.
Outcome: Clearer APIs, no casting, fewer runtime errors.
🔸 FAVOR GENERIC METHODS
Let methods declare their own
to reduce casting and overload noise.
Bonus: Generic methods compose nicely in fluent APIs.
🔸 USE BOUNDED WILDCARDS FOR FLEXIBLE APIS
PECS: Producer Extends, Consumer Super.
Rule:
- ▪️ If param produces values → ? extends T
- ▪️ If param consumes values → ? super T
🔸 CONSIDER TYPESAFE HETEROGENEOUS CONTAINERS
Key the values by type to store different types safely—no casts.
Use cases: Registries, context bags, DI-lite containers.
TAKEAWAYS
- ▪️ Generics push errors left (compile time > runtime).
- ▪️ Lists beat arrays for API design.
- ▪️ PECS makes wildcard choices straightforward.
- ▪️ Avoid @SuppressWarnings unless you can prove safety.
- ▪️ Advanced: typesafe heterogeneous containers keep flexibility and safety.
Go further with Java certification:
Java👇
Spring👇