Kim Ming Yap wrote:I have a quick questions.
According to Java SCJP by Khalid Mughal:
List a = new ArrayList(); List < ?> b; List <? extends objects> c;
According to Java SCJP by khalid mughal (a very good book!):
a = b; // ok. Widening conversion. b = a; // ok too. No unchecked warning.
b = c; // ok c = b; // ok
c=a; // ok but now will issue a unchecked warning. // clause 1
I do understand that any raw types (example a) when assigned to any bounded wilcard references, a unchecked warning is issues (since the content in that raw type a could be anything).
My questions is since c is the highest upper bound (? extends objects), shouldn't a be able to assigned to c without that warning?
I think when we try to mix the Generics with Non-Generics type then compiler issues warning.
a=b should give error because b is only a refernce type and
b=a doesnot issue warning because <?> could be anything whether Generics or Non-Generics.
b=c and c=b should also give error because none of both has been initialized
but when we do.
c=a; because now compiler knows that c is a Generics type but a is a non-generics,therefore when we try to mix Generics
and non-generics type then it will show compiles with warning.
Remeber:- compiles with warning will never be consider as a compilation failure.
a=c; is also not possible because c is also not been initialized.
List (Raw type) (eg. List a)
List <?> (eg. List b) = List <? extends objects> (eg. List c)
According to Java SCJP (Khalid Mughal):
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>
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).