2

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?

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Possible solutions could be to either have different method names, another solutions could be to use varags and make it into func(Type1... arg) and func(Type2... arg). That way you can work with arrays internally, and you can call the func with one or more Type1 or Type2s (varargs suffer from erasure).
I know that is incorrect but I want understand how it work on jdk1.6.0_43
@IgorFedorov, answer updated. I was surprised to see that it in fact worked in Java 6. Turns out it shouldn't have worked in the first place.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.