March 2, 2009

generics and instanceof

what do you think the output of the following code is?

List<Integer> list = new ArrayList<Integer>();
System.out.println(list instanceof List<Integer>);

in short: in the above code we declare list with type List<Integer>. in the next ine we try to check whether list is of type List<Integer>. the answer seems to be obvious: the output is true.

actually, the code will cause a compile-time exception with the following message

illegal generic type for instanceof

to understand this behaviour recall that generics are implemented with type erasure. that is, the resulting bytecode doesn’t contain any information about type parameters. this means that there’s no point in asking if the type of a given object is equivalent to a generic type since in the bytecode there are no generic type parameters.

java  generics 
Comments (View)
Bookmark and Share
blog comments powered by Disqus