• 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

casting doubt

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Arraylist l=new Arraylist();
l.add("samba");
l.add("siva");
String[] s=(String[])l.toArray(); //line 1


in line 1 i am getting classCastException.can anyone explain how to convert that objcet Array to string Array
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Lookup the API documentation of class ArrayList. You'll see that there are two toArray() methods: one that takes no arguments and returns an Object[], and one that does take an argument T[] and returns T[]. You need to use the second toArray() method:

String[] s = (String[]) l.toArray(new String[l.length]);
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String[] s = (String[]) l.toArray(new String[l.length]);

l.length should be repalced with l.size()

Below code works:

String[] s = (String[]) l.toArray(new String[l.size()]);

I have a doubt regarding the API for toArray in ArrayList class
API says:
public <T> T[] toArray(T[] a)

So if we are using l.toArray(new String[l.size()]), it should return String array. But if i use the below code without type cast

String[] s = l.toArray(new String[l.size()]);

I get below compile error

ArrayListTest.java:10: incompatible types
found : java.lang.Object[]
required: java.lang.String[]
String[] s = l.toArray(new String[l.size()]); //line 1

Please explain.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic