This discussion is archived
1 Reply Latest reply: Aug 17, 2010 5:50 AM by EJP RSS

Assignment of Raw types to ? extends objects

843793 Newbie
Currently Being Moderated
I am using Java SCJP (by Khalid Mughal) which i considered the best Java book which i have seen so far.
Anyway the issue i have as per below:

Object (Level 1)
!
List (Raw type) (eg. List a) (Level 2)
!
List <?> (eg. List b) = List <? extends objects> (eg. List c) (Level 3)

Say List a = new ArrayList <Integer> ();

Just talk about narrowring conversion here:
1. b = a; // ok (unbounded wildcard)
2. c=b; // ok (unbounded wildcard here is actually same as ? extends objects>
But
3. c=a; // ok but with unchecked warning.

I do understand from that book that the general rule when mixing legacy code and generic code that any assignment of raw type to BOUNDED wildcard (eg. ? extends String> will results in unchecked warning. But this rule should not be true when ? extends objects (eg list c) is used since that is the highest upper bound (covering all subtypes).

So since a (raw type) can be assigned to b (unbounded wildcard) and b is c indeed (and object is the highest upper bound), i don't see any problem here.
My opinion is a can be assigned to c (c=a) without any unchecked warning generated (since ? extends objects is the highest upper bound which will cover all subtypes).

But the book is right. I tested c=a and it does generate a unchecked warning (which means type safety can be compromised).

That's the part i don't get it
Please advice.

Edited by: yapkm01 on Aug 17, 2010 5:45 AM

Edited by: yapkm01 on Aug 17, 2010 5:45 AM

Edited by: yapkm01 on Aug 17, 2010 5:45 AM