~tak
irc.esper.net - tak, irc.freenode.com - tak11, irc.efnet.org - tak11
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Wouter Oet wrote:You want to store the elements of an Object[] into a LinkedList<T>. So every element of the array must a T or a child of T. Since there is no way to prove this for the entire array (and I'm assuming that the array not just happens to be an T[]) you'll need to cast and add every element to the LinkedList.
~tak
irc.esper.net - tak, irc.freenode.com - tak11, irc.efnet.org - tak11
Mike Simmons wrote:
The key is the double cast on line 4. The cast to raw List causes the compiler to forget the generic parameter <Object> entirely. And the cast to List<String> tells the compiler it has a new generic parameter, <String>. Casting to and from raw types would generate a warning, so using @SuppressWarnings is nice to tell the compiler to shut up about that.
Mike Simmons wrote:
For fun, try predicting what will happen with the following code. Will it compile? Will it run? Exactly what line will the error (compilation error or runtime exception) occur on? Why?
After trying to decide in advance what the answer is, try it and see. Compile it and run it (if possible), and see what happens. Was it what you expected?
~tak
irc.esper.net - tak, irc.freenode.com - tak11, irc.efnet.org - tak11
lscolton@Workstation:~/Desktop$ javac Main.java
lscolton@Workstation:~/Desktop$ java Main
[one, two, three, 4, 5, 6]
one
two
three
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at Main.main(Main.java:14)
~tak
irc.esper.net - tak, irc.freenode.com - tak11, irc.efnet.org - tak11
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
~tak
irc.esper.net - tak, irc.freenode.com - tak11, irc.efnet.org - tak11
Don't get me started about those stupid light bulbs. |