When given the specs I searched through the API and managed to find many of the requests are already implemented.
However, I'm stuck at this:
I'm supposed to do a method that takes a String array and returns an ArrayList<String> with the same objects and with the same order
This is the way I implemented my ArrayUtils class:
However, when doing:
on my UtilsTester class, I get a ClassCastException:
Exception in thread "main" java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
Why is that happening?
Arrays.asList() is supposed to return a List, so that means I can correctly cast it to an ArrayList (I guess), but I'm getting this exception.
Could you explain why?
Bear Bibeault wrote:And why do you have the urge to cast it as an ArrayList in the first place. Why isn't the List interface acceptable? Does the requirement really say it has to be an ArrayList? (Bad form if so -- coding to interfaces is much more versatile.)
Since the requirement said the method should return an ArrayList<String> that's why I tried it that way. If it was up to me, I would have used a List as you say. "Program to an interface, not an implementation".
I could run the code successfully, now, how can I do the opposite:
Is also throwing me a ClassCastException:
[Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
Bear Bibeault wrote:Look carefully at the javadoc for toArray().
Thanks for the hint, here's the solution:
Suppose l is a List known to contain only strings. The following code can be used to dump the list into a newly allocated array of String:
String x = (String) v.toArray(new String);
Note that toArray(new Object) is identical in function to toArray().