Re: Java type-casting -- Q1
grz01 wrote:
List<String> sList = new ArrayList<String>();
List<Object> oList = (List<Object>)sList;
the last assignment give me an error:
Cannot cast from List<String> to List<Object>
That is because you can only cast up to a supertype or down to a subtype, and
'List<String>' is not a subtype of 'List<Object>'.
I discovered, however, that this works:
List<String> sList = new ArrayList<String>();
List<?> oList = sList;
What's the significant difference between the two?
Peter Duniho wrote:
The "?" is a wildcard, allowing the generic type to be described as a
base type of a more specific type.
The wildcard stands for "any subtype / supertype of X", depending on the
presence of keywords "extends" or "super". The wildcard by itself stands for
"any subtype of Object". Hence, 'List<?>' can be a 'List' of "any subtype of
Object", and 'String' qualifies. Thus 'List<String>' is a valid subtype
(well, sort of) of 'List<?>'.
grz01 wrote:
Any good articles on these issues you can point me to?
Peter Duniho wrote:
I'm not sure I'd describe these two pages as "good", but they are a start:
<http://java.sun.com/docs/books/tutorial/java/generics/subtyping.html>
<http://java.sun.com/docs/books/tutorial/java/generics/wildcards.html>
Here's a good article that I've recommended two or three times in this
newsgroup in the last few days:
<http://java.sun.com/docs/books/effective/>
download the free chapter on generics
<http://java.sun.com/docs/books/effective/generics.pdf>
That chapter is a must-read for any Java programmer who wishes to make
effective use of Java generics.
Here is a two-parter by Brian Goetz:
<http://www.ibm.com/developerworks/java/library/j-jtp04298.html>
<http://www.ibm.com/developerworks/java/library/j-jtp07018.html>
--
Lew