0

As per type erasure mechanism in Java generics, a method:

boolean add(E e);

..gets compiled to

boolean add(Object e);

But then how is type safety ensured? As add now takes Object, I can pass String, Integer, Employee etc as all are sub-types of Object.

Mandroid
  • 6,200
  • 12
  • 64
  • 134
  • 3
    At the compilation stage, type information is intact, and so you cannot pass the non-E types into the method. Type safety only exists at the compilation stage. Period. – Hovercraft Full Of Eels Aug 21 '21 at 12:27
  • Don’t forget you can always just cast a generic type to a raw type and shove whatever you want in. – Boris the Spider Aug 21 '21 at 12:47
  • "gets compiled to" no, generic types in method signatures are preserved. That's how your compiler knows e.g. that `List.add(E)` requires an `E`, not an `Object`, even when you don't have the source code. (Try decompiling a generic class with `javap` to see this). – Andy Turner Aug 21 '21 at 13:03

0 Answers0