Java
Generics
Generic classes and methods.
By EZ4Code Team
genericsgeneric
Code
// Generic class
class Box<T> {
private T value;
public void set(T value) { this.value = value; }
public T get() { return value; }
}
// Generic method
public static <T> T getFirst(List<T> list) {
return list.isEmpty() ? null : list.get(0);
}
// Wildcard
public static void printList(List<?> list) {
list.forEach(System.out::println);
}
// Upper bounded wildcard
public static double sum(List<? extends Number> list) {
return list.stream().mapToDouble(Number::doubleValue).sum();
}
// Lower bounded wildcard
public static void addNumbers(List<? super Integer> list) {
list.add(42);
}Explanation
Generics provide compile-time type safety; wildcards add flexibility.
More Java Snippets
String Operations and StringBuilder
Manipulate strings with split, join, substring, and StringBuilder in Java.
Stream API
Process collections using the Stream API.
Lambda Expressions
Simplify code with Lambda expressions.
Optional
Handle null values elegantly.
Collection Operations
Common operations on List, Set, and Map.
Exception Handling
try-catch-finally and custom exceptions.