Introduction
Java introduced Generics in Java 5. Generics allow developers to write classes, interfaces, and methods that work with different data types while maintaining compile-time type safety. Instead of creating separate classes for different data types, a single generic implementation can handle multiple types efficiently.
Generics are widely used in the Java Collections Framework, custom data structures, utility methods, frameworks, and enterprise applications. They improve code reusability, eliminate unnecessary casting, and help detect errors during compilation rather than at runtime.
What are Java Generics?
Java Generics are a language feature that allows classes, interfaces, and methods to operate on different data types while ensuring compile-time type safety.
Instead of specifying a concrete data type, Generics use type parameters, which act as placeholders until a specific type is provided.
For example:
ArrayList names =
new ArrayList<>();
Here, String is the type argument, ensuring that only String objects can be stored in the list.
Why Use Generics?
Generics provide several advantages:
- Compile-time type checking
- Eliminate explicit type casting
- Improve code reusability
- Increase readability
- Reduce runtime errors
- Work with multiple data types
- Simplify API development
Without Generics, developers often need to cast objects manually, which can lead to ClassCastException.
Syntax of Generics
The basic syntax uses angle brackets (<>) to define a type parameter.
class ClassName {
}
Where:
- T represents the type parameter.
- The actual type is specified when creating an object.
Example:
Box box =
new Box<>();
Generic Class
A generic class works with different data types without rewriting the class.
Example
class Box {
private T value;
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
Using the class:
public class Main {
public static void main(String[] args) {
Box box =
new Box<>();
box.setValue("Java");
System.out.println(
box.getValue()
);
}
}
Output
The same Box class can also store Integer, Double, Character, or any other object type.
Generic Method
A method can also be generic, even if the class itself is not.
Example
public class Main {
public static void print(T value) {
System.out.println(value);
}
public static void main(String[] args) {
print("Java");
print(100);
print(3.14);
}
}
Output
100
3.14
The method automatically adapts to the supplied data type.
Generic Interface
Interfaces can also use Generics.
Example
interface Storage {
void store(T value);
T retrieve();
}
Implementation:
class StringStorage
implements Storage {
private String value;
public void store(String value) {
this.value = value;
}
public String retrieve() {
return value;
}
}
This makes interfaces flexible and reusable.
Multiple Type Parameters
A generic class can have multiple type parameters.
Example
class Pair {
private K key;
private V value;
Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
Usage:
Pair student =
new Pair<>(101, "Rahul");
Here:
- Integer is the key type.
- String is the value type.
Bounded Generics
Sometimes, a generic type should accept only certain types.
This is achieved using the extends keyword.
Example
class Calculator {
private T number;
Calculator(T number) {
this.number = number;
}
public double square() {
return number.doubleValue()
* number.doubleValue();
}
}
Valid:
Calculator c1 =
new Calculator<>(10);
Calculator c2 =
new Calculator<>(5.5);
Invalid:
Calculator c =
new Calculator<>("Java");
Because String is not a subclass of Number.
Wildcards in Generics
Java uses the ? symbol as a wildcard.
Unbounded Wildcard
List> list;
Accepts any type of list.
Upper Bounded Wildcard
List extends Number> list;
Accepts lists of Integer, Double, Float, etc.
Lower Bounded Wildcard
List super Integer> list;
Accepts Integer or its parent types.
Wildcards provide flexibility when working with collections and APIs.
Type Erasure
Java implements Generics using type erasure.
This means generic type information is removed during compilation.
For example:
ArrayList list =
new ArrayList<>();
After compilation, it behaves similarly to:
ArrayList list =
new ArrayList();
Type safety is enforced during compilation, while the compiled bytecode remains compatible with older Java versions.
Generics in Collections
Generics are heavily used in the Java Collections Framework.
ArrayList names =
new ArrayList<>();
names.add("Rahul");
names.add("Amit");
for(String name : names) {
System.out.println(name);
}
Benefits include:
- No explicit casting
- Better readability
- Compile-time type checking
Real-Life Example
Suppose an online shopping application stores different product IDs.
class Product {
private T id;
Product(T id) {
this.id = id;
}
public T getId() {
return id;
}
}
public class Main {
public static void main(String[] args) {
Product p1 =
new Product<>(101);
Product p2 =
new Product<>("A501");
System.out.println(
p1.getId()
);
System.out.println(
p2.getId()
);
}
}
Output
A501
The same class supports different ID types without duplication.
Advantages of Generics
- Compile-time type safety
- Eliminates explicit casting
- Reduces runtime errors
- Improves code reuse
- Cleaner APIs
- Better readability
- Easier maintenance
- Supports reusable libraries and frameworks
Common Mistakes
1. Using Raw Types
Incorrect:
ArrayList list =
new ArrayList();
Correct:
ArrayList list =
new ArrayList<>();
Using raw types bypasses compile-time type checking.
2. Using Primitive Types
Incorrect:
Box<int> box;
Generics work only with objects.
Correct:
Box<Integer> box;
Use wrapper classes such as Integer, Double, and Character.
3. Ignoring Type Bounds
Do not specify types that violate bounded generic constraints.
4. Excessive Wildcard Usage
Use wildcards only when they improve flexibility. Overusing them can make APIs harder to understand.
5. Assuming Generic Information Exists at Runtime
Due to type erasure, most generic type information is unavailable at runtime.
Best Practices
- Always use Generics instead of raw types.
- Use meaningful type parameter names (T, E, K, V).
- Use bounded Generics when type restrictions are needed.
- Prefer Generic methods for reusable operations.
- Avoid unnecessary wildcards.
- Use wrapper classes instead of primitive types.
- Keep Generic APIs simple and well documented.
Conclusion
Java Generics are one of the most powerful features introduced in Java 5, enabling developers to write flexible, reusable, and type-safe code. By allowing classes, interfaces, and methods to operate on different data types without sacrificing compile-time safety, Generics simplify application development and reduce common programming errors.
From generic classes and methods to bounded types, wildcards, and type erasure, Generics form the foundation of many modern Java libraries, including the Java Collections Framework. By understanding how Generics work and following best practices, you can write cleaner, safer, and more maintainable Java applications while improving both performance and developer productivity.