Compiler Error [Java123] method overloading encountered: both methods have same erasure => Java introduced generics type erasure

Scenes:

When the two parameters as follows overloaded function

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

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

IDE will report a compile error: both methods have same erasure

 

answer:

Because Java generics after erasing type at compile time, the above methods will become

void func(Map map)

 

 

Query a bit, there are a few concepts needed to understand and master.

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

Template different from Java Generics in C ++: Java generics is the "type erasure", C ++ templates are "reified the Generic" .

  • type erasure: generic type exists only during compilation, compiled byte code does not contain generic information and running, all map to the same generic type one byte code.
  • reified generic: generic type present during compilation and runtime, compiler automatically generates a generic type for each type of code and compiled into binary code.

 

The nature of type erasure

Generics (T) -> compiler (type erasure) -> original type (T replaced by Object)
generic (extends XXX?) -> compiler (type erasure) -> original type (T is XXX Alternatively)
the original type refers to the generic information is erased after the compiler, the type of the particular type of variable byte code.

resulting in limitations of the generic type erasure

Reducing the generic type erasure generalization, certain important contexts generic type can not be used, with some limitations.
 
 

Implicit type conversion runtime overhead: the use of generics, Java compiler automatically generates code to help us type conversion, which is relative to the C ++ template is undoubtedly brings additional performance overhead.

Overloaded method signatures conflict

A class can not be achieved with two variants of a generic interface

 

 

https://blog.csdn.net/abc_12366/article/details/79177328

https://blog.csdn.net/weixin_34121282/article/details/88535522  the Map Generics

 

Guess you like

Origin www.cnblogs.com/cathygx/p/11365253.html