Link to home
Create AccountLog in
Avatar of allelopath
allelopath

asked on

List<String> toArray problem

I have:
 List<String> myStringList = new ArrayList<String>();

Open in new window

then later:
myStringList.add(myString); 

Open in new window

then even later:
return (String[]) myStringList.toArray();

Open in new window


which caues the exception:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

I've referred to nothing but String in myStringList, yet it think it is list of Object.
What gives?
SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
:)
> The following is better. Otherwise (iirc) the array gets created twice

It doesn't get created twice
What CPColin suggested is the recommended approach
>>It doesn't get created twice

That's incorrect
"It" isn't created twice, but two arrays are. The array passed in is created and the array returned is created. My suggestion is shorter, at the expense of the one extra initialization; CEHJ's is slightly more efficient, at the expense of a few more characters of code (although the cast shouldn't be necessary).
>>"It" isn't created twice, but two arrays are.

Yes, that's what i meant
> at the expense of the one extra initialization

which is so small its not worth worrying about

>  (although the cast shouldn't be necessary).

its not
>>(although the cast shouldn't be necessary).

You're right - old habits die hard ;)
>>which is so small its not worth worrying about

How would you know how small that, created by reflection, would be?