重载:为什么 List<String>和 List<Integer>做出模棱两可的声明? [英] Overload: why List&lt;String&gt; and List&lt;Integer&gt; make ambiguous declaration?

查看:90
本文介绍了重载:为什么 List<String>和 List<Integer>做出模棱两可的声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如果

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

}

推荐答案

泛型只是一种编译人工制品,使代码具有更强的类型.
编译后,泛型确实被擦除了.它被称为类型擦除.
所以 ListList 就变成了 Java 字节码中的 List.
并且您不能拥有多个具有相同签名的方法.
而编译错误.
来自文档:

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 :

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

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.

这篇关于重载:为什么 List<String>和 List<Integer>做出模棱两可的声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆