Java generics name clash after type erasure
I am working on the book Java Generics and Collections and came across this piece of code that should compile and run without error
class Overloaded {
public static Integer sum(List<Integer> ints) {
int sum = 0;
for (int i : ints) sum += i;
return sum;
}
public static String sum(List<String> strings) {
StringBuffer sum = new StringBuffer();
for (String s : strings) sum.append(s);
return sum.toString();
}
}
However, this example is not compiled with the error
Error: (16, 26) java: name clash: sum (java.util.List) and sum (java.util.List) have the same erasure
I understand why this is a bug. However, the book specifically mentions that this is allowed as the compiler can distinguish the 2 methods based on the return type.
I found this thread Erasure Type and Overloading in Java: Why does it work?
It also assumes that this example should compile. Any idea what could be causing the compilation to fail?
I am using JDK 1.8. Is this recently changed from Java 1.8? In case it matters, I am using the latest IntelliJ IDEA as IDE.
source to share
As you know, in Runtime , Java will erase the generic type , so:
Integer sum(List<Integer> ints)
String sum(List<String> strings)
will be translated into Runtime :
Integer sum(List ints)
String sum(List strings)
therefore, this compiler error should be thrown out.
It compiles without error in JDK6 , this is a bug. this bug was fixed in JDK7 , so compiling with JDK8 will cause this compilation error.
Link:
source to share