2

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.

  • Are you sure the generic actually gives you any compile-time safety? I would expect `containsElement(new Integer[]{}, "String")` to compile, because `E` can be inferred to be `Object` (or `Serializable`, or `Serializable & Comparable>` etc). (Indeed, [it compiles](https://ideone.com/2WRhCM)) – Andy Turner Jun 14 '20 at 17:54
  • @AndyTurner, So what's your point ? – LennyMarshal Jun 15 '20 at 08:05
  • I'm asking what you think is "solved at compile time" by using generics. – Andy Turner Jun 15 '20 at 08:06
  • I mean to say, generics helps to avoid Type Issues at run time. Becasue generic allows to detect type issues while writing code. So if type issues are already solved at while writing code only then what's a point to convert those types to Object at run time ? I hope its clear now what am trying to ask – LennyMarshal Jun 15 '20 at 08:26

0 Answers0