简体   繁体   English

Java方法签名兼容性

[英]Java method signature compatibility

I have this sample code showing different method signatures: 我有这个示例代码显示不同的方法签名:

public class Main {
    public static interface MyMap extends Map {}
    public void func1(List<MyMap> m) {}
    public void func2(List<Map> m) {}
    public void func3(List<? extends Map> m) {}
    public void func4(List<? extends Map<?, ?>> m) {}
    public <M extends Map<?, ?>> void func5(List<M> m) {}
    public static void main(String[] args) {
        List<MyMap> myMap = null;
        Main main = new Main();
        main.func1(myMap); // OK
        main.func2(myMap); // not applicable
        main.func3(myMap); // OK
        main.func4(myMap); // not applicable
        main.func5(myMap); // OK
    }
}

When I have MyMap extending the raw type Map I have these confusions about method signature compatibility in Java. 当我让MyMap扩展原始类型Map我对Java中的方法签名兼容性有这些困惑。

As seen func1 is a control test, obviously IDE will not complain. 如图所示func1是一个控制测试,显然IDE不会抱怨。 In func2 , I can understand MyMap is not exactly a Map , hence IDE is complaining. func2 ,我可以理解MyMap并不完全是Map ,因此IDE抱怨。 After updating the signature like func3 it works again. 在像func3更新签名后,它再次起作用。 As for func4 , I sort of thinking Map<?,?> is not the same as a raw type Map , thats why IDE is complaining again? 至于func4 ,我认为Map<?,?>与原始类型Map不一样,这就是为什么IDE再次抱怨? But then what puzzles me most is func5 because it looks equivalent to func4 but IDE is not complaining? 但最让我困惑的是func5因为它看起来相当于func4但是IDE并不抱怨?

I think this was answered already: 我想这已经回答了:

Difference between Bounded Type parameter and Upper Bound Wildcard 有界类型参数与上限通配符的区别

Only exception, you added Raw Type Eresure, but I don't think it somehow influence the result. 只有例外,你添加了Raw Type Eresure,但我不认为它会以某种方式影响结果。

Also, I thinks you may find next useful: 另外,我认为你可能会发现下一个有用的:

main.func4((List<? extends Map<?, ?>>) myMap); // OK, but unchecked warning

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM