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


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


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

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 12366/article/details/79177328 34121282/article/details/88535522map generic

Similar Posts: