0

I am learning about type erasure. I know that after type erasure the generic types become either object or upper bound. But if the generic types become object is the type safety not lost?

For eg the in the below example:-

List<String> a = new ArrayList<String>();
a.add(10) // I can't do this, but after type erasure the generic type becomes object so where is 
             the check for the type?

Any help is appreciated

SuperAadi
  • 627
  • 1
  • 6
  • 15
  • 2
    Generic types guarantee type safety at compile-time. Hence, as long as we do not cast, we do not need type safety at runtime, since it was verified at compile-time. – Turing85 Jun 03 '21 at 12:45
  • ok. But I have a.add(10) for list where is the check happening? – SuperAadi Jun 03 '21 at 12:46
  • 1
    The compiler does the check and says your code is invalid. Hence you cannot build and run it. Your IDE likely reports the same thing – ssc327 Jun 03 '21 at 12:48
  • 2
    ... on the parameter of the `add(...)`-method, since it is bound to `T`, which is `String` and neither an `int` not an `Integer` is assignable to a `String`. Remember: this check is done by the compiler, not the runtime. – Turing85 Jun 03 '21 at 12:49
  • add() is bound to T, so after type erasure T becomes object right? So we will get a function with add(Object var) ? how does it verify for String or Integer or whatever T is? – SuperAadi Jun 03 '21 at 12:52
  • 1
    In fact, generic type safety is maintained by a combination of compile time and runtime. Normally, the Java compiler detects type errors; e.g. in your example. However, if your code uses raw types and / or unsafe conversions, type safety is maintained by runtime checks. For example, in `String s = list.get(0);` there is an implicit type cast of the result of `get` to a `String`. You should see the implicit typecast in the classfile as a `checkcast` instruction ... but the JIT compiler may be able to optimize it away. (See the 2nd duplink.) – Stephen C Jun 03 '21 at 14:55

1 Answers1

1

The check happens at compile time. If you compile the program example, you get the error:

error: no suitable method found for add(int)
a.add(10); 
 ^
    method Collection.add(String) is not applicable
      (argument mismatch; int cannot be converted to String)
    method List.add(String) is not applicable
      (argument mismatch; int cannot be converted to String)

This shows that the List is not letting you add the int since it is not a String and cannot be converted to a String.

Heng Ye
  • 341
  • 4
  • 17