Java - Obtaining generic object as String Generic type throws exception

Viewed 1097
public class Box<T> {
    private T element;

    public T getElement() {
        return element;
    }

    public void setElement(T element) {
        this.element = element;
    }
}

public class Test  {

    public static void main(String[] args) {
        List<Box> l = new ArrayList<>(); //Just List of Box with no specific type
        Box<String> box1 = new Box<>();
        box1.setElement("aa");
        Box<Integer> box2 = new Box<>();
        box2.setElement(10);

        l.add(box1);
        l.add(box2);

        //Case 1
        Box<Integer> b1 = l.get(0);
        System.out.println(b1.getElement()); //why no error

        //Case 2
        Box<String> b2 = l.get(1);
        System.out.println(b2.getElement()); //throws ClassCastException

    }
}

The list l holds element of type Box. In case 1, I get the first element as Box<Integer> and in second case the second element in the list is obtained as Box<String>. The ClassCastException is not thrown in the first case.

When I tried to debug, the element's type in b1 and b2 are String and Integer respectively.

Is it related to type erasure?

Ideone link

4 Answers
Related