Why doesn't this compile?
I want to know the underlying reason.
If
List<String>
List<Integer>
public String convert(List<String> strings) { return null; }
public String convert(List<Integer> strings) { return null; }
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;
}
}
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.