开发者

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

开发者 https://www.devze.com 2023-03-26 00:59 出处:网络
Consider the following simple code: List <?> list4[] = { Arrays.asList(\"1\",\"2\"), Arrays.asList(1,2)};

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  <S开发者_JAVA百科tring> 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.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消