相关疑难解决方法(0)

方法重载时重复的方法

以下代码提供编译错误,错误"重复方法"

static int test(int i){
     return 1;
}

static String test(int i){
     return "abc";
}
Run Code Online (Sandbox Code Playgroud)

这是预期的,因为重载方法具有相同的签名并且仅在返回类型方面不同.

但是下面的代码编译好了警告:

static int test1(List<Integer> l){
    return 1;
}

static String test1(List<String> l){
    return "abc";
}
Run Code Online (Sandbox Code Playgroud)

因为,我们知道Java Generics在Erasure上运行,这意味着在字节码中,这两种方法都具有完全相同的签名,并且与返回类型不同.

更令我惊讶的是,以下代码再次出现编译错误:

static int test1(List<Integer> l){
    return 1;
}

static String test1(List l){
    return "abc";
}
Run Code Online (Sandbox Code Playgroud)

如果有重复的方法,第二个代码如何工作正常而不会给出任何编译错误?

java generics overloading type-erasure erasure

5
推荐指数
1
解决办法
8723
查看次数

标签 统计

erasure ×1

generics ×1

java ×1

overloading ×1

type-erasure ×1