# Understanding Java Generics
Java generics provide type safety and eliminate the need for casting. Here’s a basic example:
import java.util.ArrayList;import java.util.List;
public class GenericsExample { public static void main(String[] args) { // Type-safe collection List<String> stringList = new ArrayList<>(); stringList.add("Hello"); stringList.add("World");
// No casting required String first = stringList.get(0); System.out.println(first); }}
Creating generic classes and methods:
public class Box<T> { private T content;
public void setContent(T content) { this.content = content; }
public T getContent() { return content; }
// Generic method public <U> void inspect(U item) { System.out.println("Box contains: " + content); System.out.println("Inspecting: " + item); }}
public class GenericMethods { // Generic method with bounded type parameter public static <T extends Number> double sum(List<T> numbers) { double total = 0.0; for (T number : numbers) { total += number.doubleValue(); } return total; }
// Wildcards for flexible method parameters public static void printList(List<?> list) { for (Object item : list) { System.out.println(item); } }}
Advanced generics with wildcards and bounds provide flexibility while maintaining type safety:
import java.util.List;
public class WildcardExample { // Upper bounded wildcard - can read but not write public static double calculateTotal(List<? extends Number> numbers) { double total = 0.0; for (Number num : numbers) { total += num.doubleValue(); } return total; }
// Lower bounded wildcard - can write but limited reading public static void addNumbers(List<? super Integer> list) { list.add(1); list.add(2); list.add(3); }}
javac GenericsExample.java && java GenericsExample