Generics in Java are a powerful feature that allows you to define classes, interfaces, and methods with type parameters. Generics provide type safety and reusability by allowing you to work with different data types while avoiding type casting and runtime errors.
Key Concepts of Generics
- Type Parameter:
- A placeholder for a type, specified within angle brackets (
<>
). - Example:
public class Box<T> { private T item; public void set(T item) { this.item = item; } public T get() { return item; } }
- A placeholder for a type, specified within angle brackets (
- Type Safety:
- Generics ensure that only the specified type can be used, reducing runtime errors.
- Without generics, you would need to cast objects explicitly, increasing the chance of
ClassCastException
.
- Reusability:
- Generic classes or methods can be reused for different data types without writing additional code.
Advantages of Generics
- Compile-Time Type Checking:
- Errors are caught during compilation rather than at runtime.
- Example:
List<String> list = new ArrayList<>(); list.add("Hello"); // list.add(123); // This will result in a compile-time error
- Elimination of Explicit Type Casting:
- Without generics:
List list = new ArrayList(); list.add("Hello"); String s = (String) list.get(0); // Manual casting
- With generics:
List<String> list = new ArrayList<>(); list.add("Hello"); String s = list.get(0); // No casting needed
- Without generics:
- Code Reusability:
- Generic methods and classes work with any type, reducing the need to write duplicate code for different types.
Examples of Generics
1. Generic Class
public class Box<T> {
private T item;
public void set(T item) {
this.item = item;
}
public T get() {
return item;
}
public static void main(String[] args) {
Box<String> stringBox = new Box<>();
stringBox.set("Hello");
System.out.println("String value: " + stringBox.get());
Box<Integer> intBox = new Box<>();
intBox.set(123);
System.out.println("Integer value: " + intBox.get());
}
}
Output:
String value: Hello
Integer value: 123
2. Generic Method
You can define a generic method within a class or interface.
public class GenericMethodExample {
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3};
String[] stringArray = {"A", "B", "C"};
System.out.println("Integer Array:");
printArray(intArray);
System.out.println("String Array:");
printArray(stringArray);
}
}
Output:
Integer Array:
1
2
3
String Array:
A
B
C
3. Generic Interface
public interface Pair<K, V> {
K getKey();
V getValue();
}
class KeyValue<K, V> implements Pair<K, V> {
private K key;
private V value;
public KeyValue(K key, V value) {
this.key = key;
this.value = value;
}
@Override