Generics in Java
Generics were introduced in Java 5 to provide a way to create reusable code that can work with different types. They add a layer of abstraction over types, allowing you to write classes, interfaces, and methods that are type-safe and easier to read.
Why Use Generics?
- Type Safety: Generics allow you to catch invalid types at compile time. For example, if you have a
ListofStrings, the compiler will prevent you from adding anIntegerto it. - Code Reusability: You can write a single generic class or method that can be used with different types.
- Elimination of Casts: Before generics, you had to use
Objectand then cast it to the correct type. This was error-prone and made the code harder to read. Generics eliminate the need for casting.
Generic Classes
You can create a generic class by specifying a type parameter in angle brackets (<>) after the class name.
Example: A Generic Box Class
Here's an example of a generic Box class that can hold any type of object:
public class Box<T> {
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
public static void main(String[] args) {
Box<String> stringBox = new Box<>();
stringBox.set("Hello");
System.out.println(stringBox.get());
Box<Integer> integerBox = new Box<>();
integerBox.set(123);
System.out.println(integerBox.get());
}
}
Explanation
<T>: This is the type parameter. You can use any valid identifier, butTfor "Type" is a common convention.private T t;: This declares a variable of typeT.public void set(T t): This method takes an object of typeT.public T get(): This method returns an object of typeT.Box<String>andBox<Integer>: When you create an instance of theBoxclass, you specify the actual type you want to use.
Generic Methods
You can also create generic methods that have their own type parameters.
Example: A Generic printArray Method
Here's an example of a generic method that can print the elements of any type of array:
public class GenericMethodExample {
public static <E> void printArray(E[] inputArray) {
for (E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
public static void main(String[] args) {
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println("Array integerArray contains:");
printArray(intArray);
System.out.println("\nArray doubleArray contains:");
printArray(doubleArray);
System.out.println("\nArray characterArray contains:");
printArray(charArray);
}
}
Explanation
<E>: This is the type parameter for the method. It's placed before the return type.E[] inputArray: The method takes an array of typeE.for (E element : inputArray): The for-each loop iterates over the elements of the array.