I am working through "Java Generics and Collections" book, and came across this piece of code, which is supposed to compile and run without errors
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 fails to compile with error
Error:(16, 26) java: name clash: sum(java.util.List) and sum(java.util.List) have the same erasure
I can understand why this is an error. However, the book specifically mentions that this is allowed, as compiler can distinguish the 2 methods based on return type.
I then found this thread Type Erasure and Overloading in Java: Why does this work?
It also suggests that this example should compile. Any idea what's causing the compile to fail?
I am using JDK 1.8. Is this recently changed with Java 1.8? In case this is relevant, I am using latest IntelliJ IDEA as IDE.