3

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.

patentfox
  • 1,436
  • 2
  • 13
  • 28

1 Answers1

5

As we know, In the Runtime, Java will erasure generic type, so:

Integer sum(List<Integer> ints)
String sum(List<String> strings)

will be translated to in Runtime:

Integer sum(List ints)
String sum(List strings)

so this compiler error should be throwed.

It compiles without throwing error in JDK6 it's a bug. this bug has been fixed in JDK7, so compile with JDK8 will throw this compile error.

Reference:

Generic class compiles in Java 6, but not Java 7

chengpohi
  • 14,064
  • 1
  • 24
  • 42
  • 3
    Actually, the type information is still there at runtime, you can even get it with reflection: `ParameterizedType pType = (ParameterizedType) Overloaded.class.getMethod("sum", List.class).getGenericParameterTypes()[0];` It's just that, if you were to call `sum` with a raw `List`, the compiler wouldn't know which method to bind. The caller would be forced to use generics to make the call not ambiguous, but that defeats the point of using a raw type. – Jorn Vernee Jun 06 '17 at 09:11