Java 5/6 Runtime Generics

Java 5/6 Runtime Generics

Please explain why the following snippet does not actually do what is intended.

if (appleList instanceof List<Apple>) { System.out.println("true"); }
javaagileAsked:
Who is Participating?
 
Sharon SethCommented:
Generics is to ensure strict type checking at compile time , to prevent a later on runtime type cast error . But this concept of Generics  is not implemented in the JVM (most probably for backward compatibility) . So , during compilation , the compiler removes the generic type (called as type erasure)  . Since instanceof is a runtime directive , and generic type info is not available at runtime , the compiler does not allow you to do it.
0
 
Sharon SethCommented:
How did you create appleList?
0
 
Sharon SethCommented:
Actually , it shld not compile , since you cannot use instanceof on a strict type . You can use it on a generic type though like List<?>
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
javaagileAuthor Commented:
I got this question on one written test. The question does not specify how appleList was created. I think you don't need to know that information to answer this question. This question is testing runtime generics.
0
 
javaagileAuthor Commented:
The answer has to be one of the following options

Runtime Generics

Explain why the following snippet does not actually do what is intended.

if (appleList instanceof List<Apple>) { System.out.println("true"); }

a) Because you do not know that appleList is a List type.
b) Because generic types are erased before runtime.
c) Because the instanceof keyword only works on primitive types.
d) Because the statement could cause appleList to be set to an instance of a List.
e) Because you can only check the type of collections using reflection.
0
 
Sharon SethCommented:
Is is an academic test?
0
 
javaagileAuthor Commented:
I need to understand why this will not work as intended
0
 
javaagileAuthor Commented:
Thanks for responding,. so what will be the answer from below options?

a) Because you do not know that appleList is a List type.
b) Because generic types are erased before runtime.
c) Because the instanceof keyword only works on primitive types.
d) Because the statement could cause appleList to be set to an instance of a List.
e) Because you can only check the type of collections using reflection.
0
 
Sharon SethCommented:
I think I have given enough explanation  for you to find the answer yourself .
 As such , experts-exchange prohibits answering test questions directly .
0
 
javaagileAuthor Commented:
Thanks that helps
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.