Tag Archives: type erasure

Compiler error encountered in [java123] method overloading: both methods have same erasure = > introduce Java generic type erasure

Scene:

When the arguments of two overloaded functions are as follows

void func(Map< Integer, String> map) {}

void func(Map< Integer, List< String>> map) {}

IDE will report compilation errors: both methods have the same erasure

Answer:

Because Java generics erase the type at compile time, the above method becomes

void func(Map map)

After a query, there are several related concepts that need to be understood and mastered

https://www.jianshu.com/p/f9da328c91be

Java generics are different from C + + templates: Java generics are “type assurance” and C + + templates are “modified generic”

Type erasure: generic types exist only during compilation. The compiled bytecode and runtime do not contain generic information. All generic types are mapped to the same bytecode

Modified generic: generic types exist during compilation and running. The compiler automatically generates type code for each generic type and compiles it into binary code

The essence of type erasure

Generics (T) – > Compiler (type erasure) – > Original type (t replaced by object)

Generic (?)?extends XXX) –> Compiler (type erasure) – > Original type (t replaced by xxx)

Primitive type refers to the specific type of type variable in bytecode after the generic information is erased by compiler.

Type erasure leads to the limitation of generics

type erasure reduces the generalization of generics, which makes it impossible to use generic types in some important contexts.

overhead of implicit type conversion at runtime: when using generics, the java compiler automatically generates code for type conversion, which undoubtedly brings additional performance overhead compared with C + + templates

overload method signature conflict

a class cannot implement two variants of the same generic interface

https://blog.csdn.net/abc_ 12366/article/details/79177328

https://blog.csdn.net/weixin_ 34121282/article/details/88535522map generic