Understanding Type Erasure in Generics
Java uses Type Erasure in Generics to ensure that no additional overhead is needed at runtime. The compiler replaces the type parameter with the Object class or the parent class (in case of bounded Generics) during the process of type erasure. In the following code block, we will see how Generics works with primitive types at compile time and runtime.
// ~/project/Main.java
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> integerList = new ArrayList<Integer>();
integerList.add(1);
integerList.add(2);
integerList.add(3);
int sum = 0;
for (int i = 0; i < integerList.size(); i++) {
sum += integerList.get(i);
}
System.out.println(sum);
}
}
To run the code, open the terminal and navigate to the ~/project
directory. Compile the code with the following command:
javac Main.java
After successful compilation, run the code with the following command:
java Main
The output of the code will be:
6
In the above code block, we tried to add the elements of the integerList
. As we know, primitive types like int
cannot be used with Generics. Due to type erasure, the type parameter Integer
is replaced with the Object class at compile time. However, autoboxing and unboxing allowed us to perform the addition of integers at compile time. At runtime, the code performed like normal code execution, without any additional overhead.