I think due to type erasure , using instanceof
and class literals
are not allowed for parameterized generic types
except unbounded wild card types
. Why did the Java language designers allowed this exception ? There isn't any role of type erasure for unbounded wild card types ?
Asked
Active
Viewed 1,285 times
6
![](../../users/profiles/1527084.webp)
Geek
- 23,609
- 39
- 133
- 212
1 Answers
8
The point is that an object knows its concrete class - but not the generic type arguments for that. So if we construct an ArrayList<Integer>
, that knows at execution time that it's an ArrayList
of some kind - but it doesn't know about the Integer
part.
The "ArrayList
of some kind" part is precisely what ArrayList<?>
means, which is why:
if (foo instanceof ArrayList<?>)
is valid. It's just equivalent to using the raw type:
if (foo instanceof ArrayList)
![](../../users/profiles/22656.webp)
Jon Skeet
- 1,261,211
- 792
- 8,724
- 8,929
-
but isn't there meta data for the compiler to say that the `field foo` is of type `ArrayList
` at run time ? I am referring to [your answer only](http://stackoverflow.com/a/339708/1527084) – Geek Feb 19 '13 at 14:05 -
@Geek: Yes, but that's for a *field*, not an *object*. They're different. – Jon Skeet Feb 19 '13 at 14:25
-
Why is checking against `ArrayList>` the same as using the raw type `ArrayList`? – sponge Jan 27 '16 at 07:45
-
@Francesco: How would you expect them to be different? – Jon Skeet Jan 27 '16 at 07:58
-
1The former uses a wildcard and is a "list of anything" while the latter omits the type parameter and is just a "list". How are they the same thing? – sponge Jan 27 '16 at 08:05
-
@FrancescoMenzani: They're the same thing at execution time due to type erasure - see the first sentence of the answer. – Jon Skeet Jan 27 '16 at 08:25
-
So when would you use one or another? Why is using the wildcard allowed if it yields the same result as the raw type? – sponge Jan 27 '16 at 09:04
-
2@FrancescoMenzani: I'm honestly not sure why it's allowed, to be honest. Maybe it's so that you can make it clear that it *is* a generic type you're testing against? – Jon Skeet Jan 27 '16 at 09:14