Androrider Androrider - 1 year ago 115
Java Question

Overload: why List<String> and List<Integer> make ambiguous declaration?

Why doesn't this compile?
I want to know the underlying reason.

If

List<String>


is not the same type as

List<Integer>


why

public String convert(List<String> strings) { return null; }


and

public String convert(List<Integer> strings) { return null; }


make an ambiguous declaration?

public class Converter {

public void why() {
List<String> strings = null;
List<Integer> integers = null;

strings = integers; // type mismatch
}

public String convert(List<String> strings) {
// error: why is this ambiguous ?
return null;
}

public String convert(List<Integer> strings) {
// error: why is this ambiguous ?
return null;
}

}

Answer Source

Generics are just a compilation artefact to make the code more strongly typed.
After compilation, generics are indeed erased. It is called type erasure .
So List<Integer> and List<String> become just List in the Java bytecode.
And you cannot have more than one method with the same signature.
Whereas the compilation error.
From the documentation :

Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to

  • Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.

  • Insert type casts if necessary to preserve type safety.

  • Generate bridge methods to preserve polymorphism in extended generic types.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download