Java Generics with Examples
Introduction
Java Generics is one of the most powerful features introduced in Java 5. It enables code reusability, type safety, and eliminates the need for explicit typecasting. Generics allow developers to define classes, interfaces, and methods with placeholder types, making the code more flexible and maintainable.
In this article, we will explore Java Generics, its advantages, and provide various examples to demonstrate its usage.
Why Use Generics?
Generics provide several benefits:
-
Type Safety: Helps detect type-related errors at compile time rather than runtime.
-
Elimination of Typecasting: Avoids explicit typecasting, making the code cleaner.
-
Code Reusability: Allows generic classes and methods to be used with different data types.
-
Compile-Time Checking: Reduces the occurrence of
ClassCastException
during execution.
Generic Classes
A generic class is a class that can work with different data types while maintaining type safety.
Syntax:
class GenericClass<T> {
private T data;
public GenericClass(T data) {
this.data = data;
}
public T getData() {
return data;
}
}
Example Usage:
public class GenericExample {
public static void main(String[] args) {
GenericClass<Integer> intObj = new GenericClass<>(100);
System.out.println("Integer Value: " + intObj.getData());
GenericClass<String> strObj = new GenericClass<>("Hello Generics");
System.out.println("String Value: " + strObj.getData());
}
}
Output:
Integer Value: 100
String Value: Hello Generics
Generic Methods
A generic method allows parameterization of methods independently of the class.
Syntax:
class GenericMethodDemo {
public static <T> void printArray(T[] elements) {
for (T element : elements) {
System.out.print(element + " ");
}
System.out.println();
}
}
Example Usage:
public class GenericMethodExample {
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4, 5};
String[] strArray = {"A", "B", "C"};
GenericMethodDemo.printArray(intArray);
GenericMethodDemo.printArray(strArray);
}
}
Output:
1 2 3 4 5
A B C
Bounded Type Parameters
We can restrict the types that can be used as type arguments by specifying an upper bound.
Syntax:
class BoundedGeneric<T extends Number> {
private T num;
public BoundedGeneric(T num) {
this.num = num;
}
public void display() {
System.out.println("Number: " + num);
}
}
Example Usage:
public class BoundedGenericExample {
public static void main(String[] args) {
BoundedGeneric<Integer> intObj = new BoundedGeneric<>(10);
intObj.display();
// BoundedGeneric<String> strObj = new BoundedGeneric<>("Hello"); // Compile-time error
}
}
Output:
Number: 10
Wildcards in Generics
Wildcards (?
) are used when the exact type is unknown.
Example of Upper Bounded Wildcard:
import java.util.*;
class WildcardExample {
public static void printNumbers(List<? extends Number> list) {
for (Number num : list) {
System.out.print(num + " ");
}
System.out.println();
}
}
Example Usage:
public class WildcardDemo {
public static void main(String[] args) {
List<Integer> intList = Arrays.asList(1, 2, 3, 4);
List<Double> doubleList = Arrays.asList(1.1, 2.2, 3.3);
WildcardExample.printNumbers(intList);
WildcardExample.printNumbers(doubleList);
}
}
Output:
1 2 3 4
1.1 2.2 3.3
Generic Interfaces
Interfaces can also be parameterized using Generics.
Syntax:
interface GenericInterface<T> {
void show(T data);
}
Example Implementation:
class GenericInterfaceImpl<T> implements GenericInterface<T> {
public void show(T data) {
System.out.println("Data: " + data);
}
}
public class GenericInterfaceExample {
public static void main(String[] args) {
GenericInterface<String> obj = new GenericInterfaceImpl<>();
obj.show("Generics in Java");
}
}
Output:
Data: Generics in Java
Conclusion
Java Generics provides a powerful mechanism to create reusable and type-safe code. It enhances code flexibility while preventing runtime errors due to incorrect type usage. Understanding and using Generics effectively helps in writing efficient and maintainable Java applications.
With the help of generic classes, methods, interfaces, wildcards, and bounded types, developers can create highly flexible and scalable applications. Generics are widely used in Java’s Collections Framework, making it an essential concept for every Java developer.
Sign up here with your email
ConversionConversion EmoticonEmoticon