Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between instanceof List and instanceof List<?> [duplicate]

I know that we cannot invoke instanceof List<E> because List<E> is not a reifiable type. Both instanceof List and instanceof List<?> work; however the eclipse IDE suggests use instanceof List<?>.

I wonder why it suggests unbound wildcard instanceof List<?> instead of raw call instanceof List. Does the unbound wildcard instanceof List<?> have any advantage over the raw call instanceof List?

Thank in advance.

Edit 1: In effect, instanceof List and instanceof List<?> is same as the compiler will erasure the type when compiling. But beside the cosmetic reason as Mena points out, does it have any other reason to use instanceof List<?> in favor of instanceof List?

Edit 2: According this entry from Oracle:

  1. The type of an instanceof/cast expression is raw

This happens very frequently, as javac forbids instanceof expressions whose target type is a generic type; for casts, the compiler is slightly more permissive since casts to generic type are allowed but a warning is issued (see above). Anyway, the raw type should be replaced by an unbounded wildcard, as they have similar properties w.r.t. subtyping.

Object o = new ArrayList<String>(); List<?> list_string = (List)o; //same as (List<?>)o boolean b = o instanceof List; //same as o instanceof List<?>

Thus, we can infer that beside the cosmetic reason as Mena said and restriction to use genenics, instanceof List and instanceof List<?> are the same.

like image 977
Linh Avatar asked Aug 05 '15 08:08

Linh


1 Answers

"List<E> is not a reifiable type" is not the best way to formulate why instanceof won't compile.

The instanceof operator verifies the type of your object at runtime.

As such, type erasure prevents Java from knowing its parametrized type (the type between the <>).

Hence a raw List (equivalent to a List<Object>) or a List<?> (i.e. a List of unknown type) practically mean the same here, although the raw syntax is usually advised against (here, for cosmetic reasons).

like image 121
Mena Avatar answered Sep 29 '22 13:09

Mena