an example of type erasure and my understanding

67 Views Asked by At
private void readList(ArrayList list){
    list.add("Hello");
    list.add(2);
}

public void run(){
    setFont("Courier-24");
    ArrayList<Integer> list = new ArrayList<Integer>();
    readList(list);
    println("list = "+list);
    println("Type of list[1] = "+list.get(1).getClass());

}

Result:
list = [Hello, 2]
Type of list[1]=class java.lang.Integer

public void run(){
    setFont("Courier-24");
    ArrayList<Integer> list = new ArrayList<Integer>();
    readList(list);
    println("list = "+list);
    println("Type of list[0] = "+list.get(0).getClass());

}


Result:
list = [Hello, 2]
Exception in thread "Thread-2" java.lang.ClassCastException:
java.lang.String cannot be cast to java.lang.Integer

After reading something about type erasure, I've got my guess:

When I call readList(list), it's actually adding things into list that is 'falsely' regarded as type ArrayList so there is no error(this is my understanding of so-called type erasure). But if I call println("Type of list = "+list.get(0).getClass()); in run() there comes the error because list[0] is of type String(while println("Type of list = "+list.get(1).getClass()); doesn't because list[1] is of type Integer).

Is it like some criminal escaped from crime scene at first (because he belongs to normal people and normal people has freedom), and later when police start to check everyone that was around then he got caught because he is a criminal in deep?

2

There are 2 best solutions below

0
On

To go along type erasure principles your method should look like

private void readList(ArrayList<Integer> list){
    list.add(1);
    list.add(2);
}

It will be apparent that adding a string to array of integers is not a good idea.

0
On

When you say

private void readList(ArrayList list){

that isn't type erasure. It is an example of a raw type. Per the Java Tutorials,

A raw type is the name of a generic class or interface without any type arguments.

before generics were added to Java there were only raw types.

In constrast type-erasure is an optimization. Generics are a compile time type check feature, there is no performance impact because the generic types are not1 checked at run-time.

1 There is a type cast inserted in the byte code.