Java Generics
What are Generics?
Generics allow classes and methods to operate on types specified as parameters, providing type safety without needing to write separate code for each data type.
List<String> names = new ArrayList<>();
names.add("Asha"); // only Strings allowed, checked at compile time
Why Generics Matter
Generics catch type mismatches at compile time rather than at runtime, and they eliminate the need for manual casting when retrieving elements from a collection.
Writing Your Own Generic Class
The type parameter, usually written as T, acts as a placeholder that is filled in when the class is used. A small wrapper for API responses shows the idea.
public class Result<T> {
private final T data;
private final int status;
public Result(T data, int status) {
this.data = data;
this.status = status;
}
public T getData() { return data; }
public int getStatus() { return status; }
}
Result<String> text = new Result<>("OK", 200);
Result<Integer> count = new Result<>(42, 200);
String s = text.getData(); // no cast needed
Integer n = count.getData();
One class now serves every type, and the compiler still knows exactly what getData() returns in each case. Without generics you would either write a separate class per type or store everything as Object and cast on every read, which moves mistakes from compile time to runtime.
Generic Methods
A method can declare its own type parameter before the return type, even inside a non-generic class.
public static <T> T firstOrDefault(List<T> items, T fallback) {
return items.isEmpty() ? fallback : items.get(0);
}
String browser = firstOrDefault(List.of("chrome", "firefox"), "edge");
Bounded Types and Wildcards
Sometimes the type must have certain abilities. A bound such as <T extends Number> limits T to numbers, so methods like doubleValue() are available.
public static <T extends Number> double average(List<T> values) {
double sum = 0;
for (T v : values) sum += v.doubleValue();
return values.isEmpty() ? 0 : sum / values.size();
}
// wildcard: read from any list of numbers
static double total(List<? extends Number> nums) { ... }
// wildcard: add Integers into a list of Integer or any supertype
static void fill(List<? super Integer> target) { target.add(1); }
A handy memory aid is "producer extends, consumer super". Use ? extends when you only read from a collection, and ? super when you only write into it. A plain ? means "any type" and suits methods that only call things like size().
Type Erasure in Plain Words
Generic type information exists only at compile time. After compiling, List<String> and List<Integer> are both just List. This is why you cannot write new T(), check obj instanceof List<String>, or overload two methods that differ only in their generic type.
Where Testers Meet Generics
List<WebElement>returned by Selenium'sfindElements.Map<String, String>for headers or test data rows.- Rest Assured's
.as(User.class)and.jsonPath().getList("items", Item.class). - Utility methods in frameworks that read any page object or data type.
- Generic data readers, for example a method that turns rows of an Excel or CSV file into a
List<T>of test data objects.
Mistakes to Avoid
- Using raw types such as plain
List, which brings back unchecked casts and runtime errors. - Trying
List<int>; type arguments must be objects, so useList<Integer>. Autoboxing converts betweenintandIntegerfor you, but watch fornullvalues, which throw an exception when unboxed. - Assuming
List<Integer>is a subtype ofList<Number>; it is not, which is why wildcards exist. - Ignoring "unchecked" compiler warnings instead of fixing the types.
- Naming type parameters with long words; the convention is single capitals such as
Tfor type,Efor element, andKandVfor map keys and values.
Ready to master real-world software testing?
Learn manual and automation testing hands-on with mentor-led sessions.