Confusion over Java generic method type inference

感情迁移 提交于 2020-01-16 05:13:10

问题


The sample method is given below:

static <T> void doSomething(List<? super T> list1, List<? extends T> list2) { }

I am wondering what type will be inferred in this situation and by what logic. Let's say I am calling this method like this:

doSomething(new ArrayList<Object>(), new ArrayList<String>());

Would T type evaluate as Object or String?


回答1:


This call does not bind T to a specific class. Java does not need to know the exact T because of type erasure implementation of the generics. As long as the types that you pass are consistent with the declaration, the code should compile; in your case, lists of Object and String are consistent with the declaration.

Let's expand your code a little so that we could force binding of T to a specific type. Perhaps the easiest way to do it is to pass Class<T>, like this:

static <T> void doSomething(List<? super T> list1, List<? extends T> list2, Class<T> cl) {
    System.out.println(cl);
}

Now let us try calling doSomething with String.class and with Object.class:

doSomething(new ArrayList<Object>(), new ArrayList<String>(), Object.class);
doSomething(new ArrayList<Object>(), new ArrayList<String>(), String.class);

Both calls successfully compile, producing the output

class java.lang.Object
class java.lang.String

Demo on ideone.



来源:https://stackoverflow.com/questions/24350273/confusion-over-java-generic-method-type-inference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!