Java Generics Wildcards: Upper Bounds and Lower Bounds, Simplified Understanding
Java generics wildcards (`?`) are used to uniformly handle generic collections of different types (e.g., `List<Integer>`, `List<Double>`) and avoid redefining methods. Wildcards are categorized into two types: **Upper Bounded Wildcard (`? extends T`)**: Elements are subclasses of `T` or `T` itself. The key characteristic is that it **can only retrieve elements** (return type is `T`), and **cannot add elements** (the compiler cannot determine the specific subclass). This is suitable for reading collection elements (e.g., printing collections of `Number` and its subclasses). **Lower Bounded Wildcard (`? super T`)**: Elements are supertypes of `T` or `T` itself. The key characteristic is that it **can only add elements** (of type `T` or its subclasses), and **cannot retrieve specific types** (only `Object` can be returned). This is suitable for adding elements (e.g., adding subclass elements to a collection whose supertype is `Number`). Core distinction: Upper bounds are "read-only", while lower bounds are "write-only". The choice depends on the scenario; avoid overusing wildcards or misusing `T`.
Read More