• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

hello, can y tell me why??

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
the key program:
ArrayList al = new ArrayList();
al.add("1");
al.add("2");
al.add("3");
al.add("4");
//this is wrong,why??
String[] str = (String[]) al.toArray();
//but this is crrect.
Object[] obj = al.toArray();
for (int i = 0; i < obj.length; i++) {
String str = (String) obj[i];
}
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The toArray() method returns an Object[]. It may contain Strings inside, but the array itself is fundamentally an Object[] not a String[], and cannot ever be cast to String[]. (String[] is a type of Object[]; and Object[] is not a type of String[].) If you want to create a String[] array (or other array type more specific than Object[]) then you must use toArray(Object[]) rather than toArray(). This allows you to create a specific type of array beforehand, and then load it in one step:

or alternately:

The second option is a bit strange - if you create an array which is the right type but too small for the size of your collection, toArray(Object[]) will merely use the type of the array provided in the argument, and will create a new array of the same type but different size. I prefer the first method as it seems more straightforward (and doesn't create an extra object which is discarded) -but either way works.
[ November 05, 2002: Message edited by: Jim Yingst ]
 
sofun
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ok,I know!
thanks!
[ November 05, 2002: Message edited by: sofun ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic