• Post Reply Bookmark Topic Watch Topic
  • New Topic

unchecked cast with bounded wildcards (although the source expression already has the right bound)  RSS feed

 
Christof Wiesmeier
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code has an unchecked warnings that i don't understand. I solved it with a wildcard capture method, but i would like to know why that is needed.


javac 1.6.0_17 with -Xlint prints:


XList's second type parameter is the same as List's sole type parameter. So I thought casting a List<type> to XList<?, type> should be fine for any type, including bounded wildcard expressions. However, it is okay for CharSequence as seen in the xlist1 assignment, but not for `? extends CharSequence' in the xlist2a assignment. Giving `? extends CharSequence' a name E via the wildcard capture method solves it (xlist2b assignment).

Can anyone please explain that? Thanks!
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With ? extends CharSequence you are saying that the type of the parameter is some type of CharSequence. So xlist2a could be an XList<?, String> while list2 could be List<StringBuffer>. Both fill the ? extends CharSequence but you can't check to make sure the cast of the object inside the List matches what is expected inside the XList.
 
Christof Wiesmeier
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply.

So xlist2a could be an XList<?, String> while list2 could be List<StringBuffer>

Yes, an XList<?, ? extends CharSequence> reference could point to an XList<?, String>, but it won't for example let me insert StringBuffers (nor the correct Strings). So i still don't see what could go wrong with xlist2a.
Besides, the xlist2b variant shows that the cast is somehow valid (or otherwise javac should probably warn on line 27, too).

So to clarify my question: Since the cast can be made checked with the capture method, shouldn't it be treated as checked in line 21, too? By capturing, i just make sure that the ?s on the left (xlist2b) and right (list2) side are the same, but what for? So maybe it is not the code's fault but rather a compiler limitation which might be fixed some day?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!