简体   繁体   中英

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 ?

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.

They are both compile-time operations.

Type erasure is translation from generic Java source code back into regular Java code (removes T , A and any other paramterized types).

Type inference can happen when a generic method is invoked or when a generic type object is created. For example, if you

class Box<T> {
    ...
}

Then when you write

Box<String> box = new Box<>();
// type parameter inferred

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM