File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Class Cast exception using ArrayList,toArray() Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Class Cast exception using ArrayList,toArray()" Watch "Class Cast exception using ArrayList,toArray()" New topic
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
    
  13

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
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Class Cast exception using ArrayList,toArray()
 
Similar Threads
exceptional messages
How to check if date/time was entered?
JSP Error
What objects eligible for GC? Considering Exception obj here an object
Exception : Server side stack traces