File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "casting doubt" Watch "casting doubt" New topic

casting doubt

sambasivarao laghuvarapu

Joined: Jun 07, 2007
Posts: 9
Arraylist l=new Arraylist();
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
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15091

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]);

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Kishore Ryali

Joined: Dec 16, 2007
Posts: 2
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 incompatible types
found : java.lang.Object[]
required: java.lang.String[]
String[] s = l.toArray(new String[l.size()]); //line 1

Please explain.
I agree. Here's the link:
subject: casting doubt
It's not a secret anymore!