Every time you write List<String> you are using generics. They let one class or method work with many types while the compiler still checks that you use them correctly. Understanding them helps you read Spring and collection code, and they come up in interviews.
Why generics exist
Before generics, a List held plain Objects. You could add a String and an Integer to the same list, and errors appeared only at runtime when casting. With List<String>, the compiler rejects an Integer immediately, and you never need to cast when reading.
A generic class
public class ApiResponse<T> {
private final T data;
private final String message;
public ApiResponse(T data, String message) { this.data = data; this.message = message; }
public T getData() { return data; }
}
Now ApiResponse<Course> and ApiResponse<List<Student>> both work with one class.
A generic method
public static <T> T firstOrDefault(List<T> items, T fallback) {
return items.isEmpty() ? fallback : items.get(0);
}
The <T> before the return type declares the type parameter.
Bounded types
<T extends Number> limits T to Number and its subclasses, so inside the method you can call doubleValue(). This is how you write one method that sums Integers, Doubles or Longs.
Wildcards
List<? extends Number>: a list of some subtype of Number. Good for reading.List<? super Integer>: a list that accepts Integers. Good for writing.
A useful memory aid is “producer extends, consumer super” (PECS).
Type erasure
Generic type information is removed after compilation, so at runtime a List<String> is just a List. That is why you cannot write new T() or check instanceof List<String>. Interviewers often ask about this.
Related: Java collections, Java records and ArrayList vs LinkedList.
These topics are practised with projects and mock interviews in our Java Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
