| Author |
Class Cast exception using ArrayList,toArray()
|
Tony Evans
Ranch Hand
Joined: Jun 29, 2002
Posts: 521
|
|
Hi I have the following code that is causing a Exception java.lang.ClassCastException. String [] files = (String []) arrList.toArray(); Can anyone shed any light on this. Thanks for anyhelp. Tony
|
 |
Scott Selikoff
Saloon Keeper
Joined: Oct 23, 2005
Posts: 3652
|
|
The method toArray() converts to the type Object[] and this cannot be cast down to String[]. You have to provide an argument to the method specifying the type such as toArray(new String[size]) where size can be specified as the same, smaller than or greater than depending on your needs From the API: array param - the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
|
My Blog: Down Home Country Coding with Scott Selikoff
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
You need to use the other version of toArray that specifies the runtime type of the array returned. (String[])arrList.toArray(new String[0]);
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24057
|
|
|
We just discussed this one ad nauseum here.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Scott Selikoff
Saloon Keeper
Joined: Oct 23, 2005
Posts: 3652
|
|
Originally posted by Ernest Friedman-Hill: We just discussed this one ad nauseum
It's like groundhog day where every day you discuss the same topic over and over again...
|
 |
Tony Evans
Ranch Hand
Joined: Jun 29, 2002
Posts: 521
|
|
LOL thanks actually I solved the problem and this is my snippet of code : String files [] = (String []) arrList.toArray (new String [arrList.size ()]); Thanks again Tony
|
 |
 |
|
|
subject: Class Cast exception using ArrayList,toArray()
|
|
|