Unbounded wildcard passed to method

巧了我就是萌 提交于 2019-12-05 22:55:50

This is due to capture conversion. Internally, compiler converts the type of an expression Foo<?> to Foo<X>, where X is a specific albeit unknown type.

The compiler is free to infer anything that is compatible with the types of the arguments and return type. In your case it can always infer T as Object. Which turns the signature into

static Object wildSub(ArrayList<?> holder, Object arg)

Which means it can take any ArrayList as first argument and anything as second. Since you don't do anything with the return value, Object will be okay.

If you think about it as the compiler using Object where ? is used, it makes sense why it would compile. That is all there is to it.

If you are doing any operations dependent on ? being a certain class, you will get a cast exception at run time if the wrong class is passed in.

As an addition to existing (correct) answers to make it more clear:

    ...
        Object result1 = ColTest.wildSub(list, lng); //compiles fine with Sun's javac
//      Long result2 = ColTest.wildSub(list, lng);   //does not compile without explicit casting
        Long result2 = (Long) ColTest.wildSub(list, lng);   //compiles fine 
    ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!