In Java, Generics provide a way to create classes, interfaces, and methods with type parameters. They allow you to write more general, type-safe, and reusable code.
๐น Why Use Generics?
Without generics:
- You use
Object
, and casting is required. - Type safety is not enforced at compile time.
With generics:
- Type safety: Errors are caught at compile time.
- Code reusability: One class can work with many data types.
- Eliminates casting: The compiler automatically knows the type.
๐น Basic Generic Class Example
class Box<T> {
private T value;
public void set(T value) {
this.value = value;
}
public T get() {
return value;
}
}
Usage:
public class GenericTest {
public static void main(String[] args) {
Box<Integer> intBox = new Box<>();
intBox.set(123);
System.out.println(intBox.get());
Box<String> strBox = new Box<>();
strBox.set("Hello");
System.out.println(strBox.get());
}
}
๐น Generic Method Example
public class GenericMethodExample {
public static <T> void printArray(T[] array) {
for (T item : array) {
System.out.println(item);
}
}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3};
String[] strArray = {"A", "B", "C"};
printArray(intArray);
printArray(strArray);
}
}
๐น Generic Interface Example
interface Printer<T> {
void print(T item);
}
class StringPrinter implements Printer<String> {
public void print(String item) {
System.out.println("Printing: " + item);
}
}
๐น Bounded Type Parameters
You can restrict a type parameter to a certain class or interface using extends
.
class NumberBox<T extends Number> {
private T number;
public NumberBox(T number) {
this.number = number;
}
public double getDoubleValue() {
return number.doubleValue();
}
}
๐น Wildcards in Generics
Wildcard | Meaning |
---|---|
<?> |
Unbounded wildcard (any type) |
<? extends T> |
Upper bound (T or subtype) |
<? super T> |
Lower bound (T or supertype) |
Example:
public static void printList(List<?> list) {
for (Object obj : list) {
System.out.println(obj);
}
}
๐น Generics with Collections
List<String> names = new ArrayList<>();
names.add("Alice"); // Type safe
// names.add(123); // Compile-time error
๐น Type Erasure
At runtime, all generic type information is erased. This means:
-
List<String>
andList<Integer>
become justList
. - You cannot use primitives (like
int
) directly โ useInteger
,Double
, etc.
๐น Summary
Feature | Benefit |
---|---|
class<T> |
Generic class |
<T> methodName() |
Generic method |
interface<T> |
Generic interface |
T extends Class |
Bounded type |
<?> , <? extends> , <? super>
|
Wildcards |
Would you like examples using generics in real-world scenarios like a repository class, a utility class, or a comparator?
Top comments (0)