Alex Rivera | Logout

What is the concept of erasure in generics in Java?

Asked 2008-11-24T07:20:47.823
158

What is the concept of erasure in generics in Java?

Edit
Report

2 Answers

32

Erasure, literally means that the type information which is present in the source code is erased from the compiled bytecode. Let us understand this with some code.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class GenericsErasure {
    public static void main(String args[]) {
        List<String> list = new ArrayList<String>();
        list.add("Hello");
        Iterator<String> iter = list.iterator();
        while(iter.hasNext()) {
            String s = iter.next();
            System.out.println(s);
        }
    }
}

If you compile this code and then decompile it with a Java decompiler, you will get something like this. Notice that the decompiled code contains no trace of the type information present in the original source code.

import java.io.PrintStream;
import java.util.*;

public class GenericsErasure
{

    public GenericsErasure()
    {
    }

    public static void main(String args[])
    {
        List list = new ArrayList();
        list.add("Hello");
        String s;
        for(Iterator iter = list.iterator(); iter.hasNext(); System.out.println(s))
            s = (String)iter.next();

    }
} 
answered 2011-12-13T09:32:47.170
26

To complete the already very complete Jon Skeet's answer, you have to realize the concept of type erasure derives from a need of compatibility with previous versions of Java.

Initially presented at EclipseCon 2007 (no longer available), the compatibility included those points:

  • Source compatibility (Nice to have...)
  • Binary compatibility (Must have!)
  • Migration compatibility
    • Existing programs must continue to work
    • Existing libraries must be able to use generic types
    • Must have!

Original answer:

Hence:

new ArrayList<String>() => new ArrayList()

There are propositions for a greater reification. Reify being "Regard an abstract concept as real", where language constructs should be concepts, not just syntactic sugar.

I should also mention the checkCollection method of Java 6, which returns a dynamically typesafe view of the specified collection. Any attempt to insert an element of the wrong type will result in an immediate ClassCastException.

The generics mechanism in the language provides compile-time (static) type checking, but it is possible to defeat this mechanism with unchecked casts.

Usually this is not a problem, as the compiler issues warnings on all such unchecked operations.

There are, however, times when static type checking alone is not sufficient, like:

  • when a collection is passed to a third-party library a
answered 2008-11-24T07:38:50.283

Your Answer