• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Tim Cooke
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
Saloon Keepers:
  • Piet Souris
Bartenders:

Class Cast exception using ArrayList,toArray()

 
Ranch Hand
Posts: 681
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
author
Posts: 4356
45
jQuery Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You need to use the other version of toArray that specifies the runtime type of the array returned.

(String[])arrList.toArray(new String[0]);
 
author and iconoclast
Posts: 24208
47
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
We just discussed this one ad nauseum here.
 
Scott Selikoff
author
Posts: 4356
45
jQuery Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 681
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic