javagenericsterminologytype-inferencetype-erasure

Java - What's the difference between type erasure and type inference?


What's the difference between type erasure and type inference? Are they both compile-time operations?

Type Erasure: which removes the generic type information at compile time process.

  • Example: Box<String> is translated to type Box, which is called the raw type.

How Type Inference is different from type Erasure?
Before JDK 7:

Box<String> box=new Box<String>();

From JDK 7:

 Box<String> box=new Box<>();

My guess the above examples are Type Inference. Is that right?

Is Type Inference is opposite to Type Erasure?


Solution

  • Both of them serve completely different needs:

    Type erasure is like you said and is needed because java byte code is not generic hence you need to remove the typing. This isn't a feature that helps you code it's just an automatic compile time change that has to happen for the jvm to understand your code.

    Type inference on the other hand is the compiler being "smart" and knowing what type you were referring to even though you didn't actually write it. Just like in your example the compiler knows that Box<>() actually means Box<String>() and lets you continue coding with type safety as if you wrote Box<String>. This way you can write less verbose code and the compiler would still understand it.

    You can understand from all of this that generics in Java are actually mostly a compile time thing that lets you code with more safety and helps you find errors in compile-time rather than run-time.