Do two separate types have the same erase?

I stumbled upon an interesting mistake that I had never seen before, and cannot explain why

Consider the following class

public class Sandbox<A,B> { public void put(B b) { } public void put(A a) { } } 

Looks good to my eyes. So I compile it and then I get this

 name clash: put(B) and put(A) have the same erasure 

A? How do two different common types have the same signature? There is completely separate!

I probably missed something completely basic, but I just hadn't encountered this problem before. I took advantage of group support by calling putA and putB , but I'm really curious why this error occurred in the first place.

Will anyone reason?

+4
source share
4 answers

Logically consider the following code:

 SandBox<String, String> sandBox = new SandBox<String, String>(); sandBox.put("foo"); // which put is invoked? 

(Although I must admit that it is possible to create completely correct code that creates similar situations - and then the method is chosen with "random".)

Formally, I think this JLS section is relevant. Both put versions have the same argument types - if I read this section correctly.

+17
source

Generics in Java are only available at the code level, not at run time.

So, when the compiler translates your source code, the types you specified for A and B are β€œerased”. This means that both types are set to java.lang.Object .

So you get two identical method signatures.

+3
source

How do two different types work with the same signature? There are completely separate!

Java generators are based on the erase dash . This means that your code basically compiles with this:

 public class Sandbox{ public void put(Object b) { } public void put(Object a) { } } 
+1
source

A? How do two different common types have the same signature? There is completely separate!

The root of your problem is that you are not very good at Java terminology.

The compiler does not tell you that two types of a common type have the same signature:

  • Types (general or other) do not have a signature in the formal sense. Methods have signatures.

  • A and B are not typical types. They are type parameters.

  • What the compiler tells you has the same signature: put(A) and put(B) . These are methods, not types.

EDIT

OK ... so you understand the terminology.

If you use technical terminology incorrectly, do not be surprised if:

  • Some people misinterpret your questions (and answers),
  • some people call you the wrong terminology and
  • some people throw off what you ask / talk about as ignorant.

But the case I’m most worried about (and the real reason I took the time to answer your question !!) when some kind of bad confused Java newbie does a google search finds your SO question completely careless terminology and becomes even more confusing.

+1
source

All Articles