重载:为什么List <String>和List <Integer>会产生不明确的声明?

And*_*der 1 java overloading ambiguity

为什么不编译?我想知道根本原因.

如果

 List<String> 
Run Code Online (Sandbox Code Playgroud)

与...不是同一类型

 List<Integer> 
Run Code Online (Sandbox Code Playgroud)

为什么

public String convert(List<String> strings) { return null; }
Run Code Online (Sandbox Code Playgroud)

public String convert(List<Integer> strings) { return null; }
Run Code Online (Sandbox Code Playgroud)

做一个模棱两可的宣言?

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

dav*_*xxx 7

泛型只是一个编译工具,可以使代码更强类型化.
编译后,泛型确实被删除了.它被称为类型擦除.
所以List<Integer>,List<String>变成ListJava字节码.
并且您不能拥有多个具有相同签名的方法.
而编译错误.
文档:

泛型被引入到Java语言中,以便在编译时提供更严格的类型检查并支持泛型编程.为了实现泛型,Java编译器将类型擦除应用于

  • 如果类型参数是无界的,则用泛型或对象替换泛型类型中的所有类型参数.因此,生成的字节码仅包含普通的类,接口和方法.

  • 如有必要,插入类型铸件以保持类型安全.

  • 生成桥接方法以保留扩展泛型类型中的多态性.