You'd need a separate overloaded printArray for int[], double[], String[] … — repetitive, hard to maintain.
<T> — the type parameter<T> void method(T x)T (Type), E (Element), K,V (Key,Value)At compile time, generic type info is used for checking, then largely erased — the compiled bytecode mostly just uses Object, with the compiler inserting the right casts automatically.
Just like regular methods, generic methods can be overloaded by having different parameter lists (e.g. one version taking two Ts, another taking three).
Write the class logic once (like a custom Stack<T> or Pair<K,V>) and reuse it safely with any object type, with the compiler enforcing consistency.
| Wildcard | Meaning |
|---|---|
List<?> | list of unknown type — read-only |
List<? extends Number> | Number or any subclass — safe to read |
List<? super Integer> | Integer or any superclass — safe to write |
| Syntax | Meaning |
|---|---|
<T> void method(T x) | generic method with type parameter T |
<T extends Comparable<T>> | bounded type parameter — T must implement Comparable |
class Box<T> { } | generic class with type parameter T |
class Pair<K,V> { } | generic class with two type parameters |
List<?> | unbounded wildcard — unknown element type |
List<? extends T> | upper-bounded wildcard — read-only producer |
List<? super T> | lower-bounded wildcard — write-safe consumer |