Instance for common with <?> Or without <?>
I have a question about generics in Java and the instanceof operator.
It is not possible to make such a validation instance:
if (arg instanceof List<Integer>) // immposible due to // loosing parameter at runtime but you can run this:
if (arg instanceof List<?>)
Now my question is , is there a difference between arg instanceof List and arg instanceof List<?> ?
Java Generics are implemented by erasing, that is, additional type information ( <...> ) will not be available at run time, but will be deleted by the compiler. This helps when checking for a static type, but not at runtime.
Since instanceof will check at runtime, not at compile time, you cannot check the Type<GenericParameter> in the instanceof ... statement.
As for your question (you probably already know that the general parameter is not available at runtime), there is no difference between List and List<?> . The latter is a wildcard, which basically expresses the same thing as a type without parameters. This is a way to tell the compiler "I know that I do not know the exact type here."
instanceof List<?> comes down to instanceof List - exactly the same.
List and List < ? > List and List < ? > do not match, but in this case, when you use the instanceof operator, they mean the same thing.
instanceof cannot be used with Generics, since Generics does not save type information at runtime (due to erasure implementation).
This point is cleared below the main method. I declared two lists (one of type Integer and another of type String). And instanceof behave the same for List and List < ? > List and List < ? >
public static void main(String[] args){ List<Integer> l = new ArrayList<Integer>(); List<String> ls = new ArrayList<String>(); if(l instanceof List<?>){ System.out.print("<?> "); } if(l instanceof List){ System.out.print("l "); } if(ls instanceof List<?>){ System.out.print("<?> "); } if(ls instanceof List){ System.out.print("ls "); } } output: <?> l <?> ls
In the main method above, all if statements are true. Therefore, it is clear that in this case the List and List<?> same.