yapkm01
yapkm01

Reputation: 3775

Java Generics - Unbounded wildcard allows mixture of different types (no warning)

Consider the following simple code:

List <?> list4[] = { Arrays.asList("1","2"), Arrays.asList(1,2)};

I do understand that unbounded wildcard is a reifiable type; hence i do understand why the above works without any problem (without any unchecked warning)

However if you look at it carefully, the above code will produce a problem now.
There is a mixture of List <string> and List <Integer> in the array. Shouldn't special circumstances like the above have a unchecked warning?

List  <String> x = list4[0];  
List  <String> y = list4[1]; <-- problem right?  

I know this is ridiculous example but it is just an example where issue arises where there is a mixture of type in a common container.

Upvotes: 2

Views: 385

Answers (1)

erickson
erickson

Reputation: 269627

Why is it a problem?

To be more pointed: please provide some code that raises a ClassCastException in the absence of a cast to demonstrate how it is a problem. Type safety warnings are provided when code can create a type error at runtime even though no explicit casts are used.


In order to make the proposed assignments compile, a cast must be added:

List<String> x = (List<String>) list4[0];

However, a cast to a parameterized type will produce a type safety warning. Because Java's generic types are not reified, the necessary information for type checking will not be available at runtime. The warning let's you know that if you perform such a cast, you might have ClassCastException at points in your code where there are no explicit casts. For example:

List<String> y = (List<String>) list4[1]; /* Ignore the warning... */
...
...
String s = y.get(0); /* Throws ClassCastException, even though there's 
                        no (explicit) cast at this location! */

The correct way to use such an array would be to assign to an unbounded type:

List<?> y = list4[1];
Object z = y.get(0);

Upvotes: 3

Related Questions