Java generic type parameters

I have a method that uses 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 the method, how do I know whether arg is a list of classA or a list of ClassB?

Solution

From the user's answer "if you use " called Romain, you mean you won't use parameterized types anywhere Either go to a specific type (in your case, it seems to be list < string >) or to a very general list < Object >“

In addition, I believe that if you use question marks, the compiler will not catch type mismatches until runtime (implemented; page 119 of Java), bypass erasure, and effectively eliminate the benefits of using generic types???

Answer the questioner's question: if you use list < Object > and try to convert it to a or B, you may use instanceof, which may be a way to tell it what it is I bet there is a better way to do this

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>