Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instanceof with generic collection

Tags:

java

Why would the following snippet not compile ?

if (mangoList instanceof List<Mango>) { System.out.println("true"); }
  • You don't know that mangoList is a List type.
  • The instanceof keyword only works on primitive types.
  • You can only check the type of collections using reflection.
  • Generic types are erased before runtime.(ans)
  • The statement could cause mangoList to be set to an instance of a List.

Which do you think is the correct answer ?

like image 470
Ujwol Shrestha Avatar asked Jul 16 '12 00:07

Ujwol Shrestha


1 Answers

The correct answer is the one that you marked ans. You will be able to tell that mangoList is a List, but you wouldn't be able to get the type of its erased argument. The remaning choices do not make sense.

like image 135
Sergey Kalinichenko Avatar answered Sep 26 '22 03:09

Sergey Kalinichenko