Mastering Wildcards and Bounded Generics in Java

☀️ Day 13 of My 90 Days Java Challenge – Wildcards & Bounded Generics Today I dove deeper into Generics, exploring the part most beginners skip: wildcards and bounds. At first, ?, ? extends, ? super looked like confusing symbols. But once I understood their purpose, everything clicked — they’re not just syntax, they’re contracts that enforce safe and flexible code. Here’s what I realized 👇 🔹 1️⃣ Unbounded wildcard (?) – the “I don’t care” placeholder List<?> means “a list of some type, I don’t know which.” It’s great for read-only access when you want generic methods that accept any collection. Most beginners misuse it by trying to add elements — but that’s exactly what it prevents safely. 🔹 2️⃣ Upper bounded wildcard (? extends) – safe reading List<? extends Number> lets you read elements as Number or its parent types. It allows flexible input while preventing unsafe writes. The lesson: upper bounds are for producers — if you’re only consuming data, use extends. 🔹 3️⃣ Lower bounded wildcard (? super) – safe writing List<? super Integer> allows adding Integer or its subclasses. It’s for consumers — if your method is mainly writing into the collection, lower bounds give flexibility without breaking type safety. 🔹 4️⃣ PECS principle – Producer Extends, Consumer Super This is the golden rule: If your collection produces data, use ? extends. If your collection consumes data, use ? super. Ignoring this principle often leads to messy, type-unsafe code. 💭 Key takeaway: Wildcards aren’t just a syntax quirk — they’re a powerful tool for safe abstraction. Understanding them transforms your generics from “just type placeholders” to real contracts that guide safe, flexible design. #Day13 #Java #CoreJava #Generics #Wildcards #TypeSafety #springboot #advanceJava #LearningJourney #90DaysChallenge

To view or add a comment, sign in

Explore content categories