I have a question about generics in Java and instanceof
operator.
It's immposible to make such instanceof check:
if (arg instanceof List<Integer>) // immposible due to
// loosing parameter at runtime
but it's possible to run this one:
if (arg instanceof List<?>)
Now comes my question - is there any difference between arg instanceof List
and arg instanceof List<?>
?
6. instanceof and Generics. Instance tests and casts depend on inspecting the type information at runtime. Therefore, we can't use instanceof along with erased generic types.
No, a null check is not needed before using instanceof. The expression x instanceof SomeClass is false if x is null . The Java 11 Language Specification expresses this concisely in section 15.20. 2, "Type comparison operator instanceof".
The question mark ( ? ) wildcard character can be used to represent an unknown type using generic code. Wildcards can be used with parameters, fields, local variables, and return types.
instanceof is a keyword that is used for checking if a reference variable is containing a given type of object reference or not.
Java Generics are implemented by erasure, that is, the additional type information (<...>
) will not be available at runtime, but erased by the compiler. It helps with static type checking, but not at runtime.
Since instanceof
will perform a check at runtime, not at compile time, you can not check for Type<GenericParameter>
in an instanceof ...
expression.
As to your question (you probably seem to know already that the generic 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 the type without parameters. It's a way of telling the compiler "I know that I don't know the exact type in here".
instanceof List<?>
boils down to instanceof List
- which are exactly the same.
List and List < ? >
are not same but in this case when you using with instanceof operator they mean the same thing.
instanceof cann't be used with Generics as Generics doesn't store any type information at run time (due to erasure implementation).
This point gets cleared by below main method. I have declared two list (one of Integer type and other of String type). And instanceof behave same for 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 is :
<?> l <?> ls
In above main method all if statements are true. So it clear that in this case List and List<?>
are same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With