Type Erasure in Java

To support generic programming, as well as perform a stricter type check, Java implements type erasure.

  • All type parameters in generic types are replaced with the bound (if unbounded) or object type. This way, the bytecode will only contain classes, methods, and interfaces.

  • Type casts to preserve the type.

  • Bridge methods are generated so as to preserve the polymorphism concept in extended generic types.


 Live Demo

import java.io.PrintStream;
import java.util.*;
public class Demo{
   public Demo(){
   public static void main(String args[]){
      List my_list = new ArrayList();
      my_list.add("Hi there");
      String my_str;
      for (Iterator iter = my_list.iterator(); iter.hasNext();
      my_str = (String)iter.next();


Hi there

A class named Demo contains a constructor that basically has no body defined inside it. In the main function, a new array list is created, and elements are added into it using the ‘add’ function. An iterator is defined, and a string is defined. An iterator iterates over the elements in the string using the ‘hasNext’ function that checks if there is an element and then moves over to it. The output is printed on the screen.

Updated on: 17-Aug-2020


Kickstart Your Career

Get certified by completing the course

Get Started