且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java泛型类型参数

更新时间:2022-10-16 17:23:36

来自罗曼的用户的回答如果您使用&lt ;?>,则表示您不打算在任何地方都可以使用参数化类型,或者转到特定的类型(在你的情况下,它似乎是List< String>)或者到非常通用的List< Object>的类型。 ,我相信如果你使用问号,那么编译器不会直到运行时才捕获类型不匹配(有效Java的p.119),绕过擦除,并有效地减少使用泛型类型获得的好处???



回答提问者的问题:如果您使用List< Object>,然后尝试将它转换为A或B,可能使用instanceOf,这可能是一种告诉它是什么的方法。我敢打赌,有一种更好的方法可以做到这一点。


I have a method which takes a List<?> as an argument.

public static String method(List<?> arg){
     // Do something based on type of the list
}

//I call the method as below
List<ClassA> listA = new ArrayList<ClassA>();
List<ClassB> listB = new ArrayList<ClassB>();
method(listA);
method(listB);

In method, how do I know if arg is a List of ClassA or a List of ClassB?

From an answer by the user called Romain " If you use < ?>, you mean you aren't going to use the parametrized type anywhere. Either go to the specific type (in your case it seems List< String>) or to the very generic List< Object> "

Also, I believe that if you use the question mark the compiler wont catch type mismatches until runtime (reified; p.119 of Effective Java), bypassing erasure, and effectively elimating the benefit you get from using generic types???

TO answer the question of the questioner: if you use List< Object> and then try to cast it to A or to B , possibly using instanceOf , that might be a way to tell what it is. I bet there is a better way to do it than that though.