Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two separate generic types have the same erasure?

Tags:

java

generics

I stumbled upon an interesting error that I've never seen before, and can't explain why

Consider the following class

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

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

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

Huh? How do two different generic types have the same signature? There completely separate!

I'm probably missing something completly basic, but I've just not run into this issue before. I've band-aid fixed the problem by calling the methods putA and putB, but I'm really curious to why this error happened in the first place.

Would someone mind explaining?

like image 382
TheLQ Avatar asked Nov 29 '22 05:11

TheLQ


1 Answers

Logically, consider the following code:

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

(Although I should admit that it's possible to produce perfectly valid code that produces similar situations - and then a method is chosen at "random".)

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

like image 90
waxwing Avatar answered Dec 09 '22 19:12

waxwing