简体   繁体   中英

Overload java method by List<>

I have the code, where methods is overlays with List<> arguments

RetrunType1 func(List<Type1> arg);
ReturnType2 func(List<Type2> arg);

and Type1!=Type2, but that code compile and work fine on jdk1.6.0_45. I know that this sample don't compile and work. How I can understand that?

This is due to type erasure . The generic type parameters do not follow through to the byte code, so if the overloading you suggest would be legal, you would end up with a name collision in the byte code:

ReturnType1 func(List arg);
ReturnType2 func(List arg);

The solution is to use different names for the functions.

The reason it worked in Java 6 was due to a bug that was fixed in Java 7.

The problem here is something called type erasure which you can read about here . The short version is however, that the Java compiler will remove the generic arguments so as to make the byte code compatible to previous Java versions. So both methods have the signature

RetrunType1 func(List arg);
ReturnType2 func(List arg);

So to Java those functions look pretty much the same.

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