Erased type to Object in Java generics

Viewed 31

Type erasure can be explained as the process of enforcing type constraints only at compile time and discarding the element type information at runtime.

public static  <E> boolean containsElement(E [] elements, E element){
    for (E e : elements){
        if(e.equals(element)){
            return true;
        }
    }
    return false;
}

The compiler replaces the unbound type E with an actual type of Object:

public static  boolean containsElement(Object [] elements, Object element){
    for (Object e : elements){
        if(e.equals(element)){
            return true;
        }
    }
    return false;
}

My concern is, When collection loading check is successfully verified at compile time using generic type, then what's a point of converting generic specified type to Object at run time ? Because main purpose of avoding type issue is already solved at compile time.

0 Answers
Related