Java Generics is one of the MOST important Java concepts.
If you understand Generics properly:
collections become safer
code becomes reusable
compile-time bugs reduce dramatically
A generic type is a generic class or interface that is parameterized over types.
What Are Generics?
Generics allow classes, interfaces, and methods to work with:
different data types safely
without rewriting code.
The Diamond
In Java SE 7 and later, you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments (<>) as long as the compiler can determine, or infer, the type arguments from the context. This pair of angle brackets, <>, is informally called the diamond. For example, you can create an instance of Box with the following
statement:
Box<Integer> integerBox = new Box<>();
Generic Class
class Box<T> {
T value;
void set(T value) {
this.value = value;
}
T get() {
return value;
}
}
Usage
Box<String> box =
new Box<>();
box.set("Hello");
String s = box.get();
What Does Mean?
T means:Type parameter
Placeholder for actual type.
Common Generic Type Names
Symbol - Meaning
T - Type
E - Element
K - Key
V - Value
N - Number
Same class reused.
Box<Integer> intBox = new Box<>();
Box<String> strBox = new Box<>();
DISADVANTAGES OF GENERICS
Now let us discuss the IMPORTANT limitations.
1. Type Erasure
MOST IMPORTANT limitation.
Java removes generic type information at runtime.
Example
List<String> list = new ArrayList<>();
At runtime becomes: List
Generic type removed. Why?
Backward compatibility with old Java.
Consequences of Type Erasure
Cannot Do This
if(obj instanceof List<String>)
Compile-time error.
Cannot Create Generic Array
T[] arr = new T[10];
Not allowed. Why?
Because runtime type unknown.
2. Primitive Types Not Allowed
Cannot use: List<int>
Only objects allowed.
Correct List<Integer>
Uses wrapper classes.
Problem
Wrapper classes add:
memory overhead
boxing/unboxing cost
Example
List<Integer> list = new ArrayList<>();
list.add(10);
Actually becomes:
Integer.valueOf(10)
Auto-boxing.
3. Cannot Create Static Generic Fields
Invalid
class Test<T> {
static T value;
}
Why?
A static field belongs to the class,
but a generic type belongs to the object instance/type parameter.
These two concepts conflict.
First Understand Static Variables
Static variables are:shared across ALL objects
Only ONE copy exists.
Top comments (0)