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 Class Cast Exception - Please help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Class Cast Exception - Please help" Watch "Class Cast Exception - Please help" New topic

Class Cast Exception - Please help

Kishan Kumar
Ranch Hand

Joined: Sep 26, 2000
Posts: 130
Hi folks,
I have string objects in a vector.
When I try to use Vector.toArray() and type cast the object array returned to a String[] class cast exception at runtime is occurring. Iam not able to understand why. All inside are string objects and if String[] is not returned to what object array can this object[] be succesfully typecasted. Or in other words what should I do to pull elements from vector to form a String array.
My other question is how to sort elements inside a vector. I want the sorted elements to be agiain in a Vector itself.
Thanks for your time.

V. Kishan Kumar

Regards,<BR>V. Kishan Kumar
Christopher Gregory

Joined: Feb 08, 2001
Posts: 4
Hey Kishan, I've run into the problem you are facing before. I don't think your cast will work because the array used by a Vector is of type Object[]. Although, it contains String objects you can't cast the array Object to another type, in other words you can't cast the Object[] to a String[] because it was never of type String[]. To return an array of Strings you can use the other toArray method: toArray(Object []a) where the array specified as an argument dictates the type of the returned's an example:
class VectorTest {

public static void main(String [] args) {

Vector v = new Vector();
String[] strArray= (String []) v.toArray(new String [v.size()]);
for (int i = 0; i < strArray.length; i++)

the output should be:
Hope this helps!
Kishan Kumar
Ranch Hand

Joined: Sep 26, 2000
Posts: 130
Thanks very much. You were able to explain what I wanted.
As far as second question I got the answer..
we can use Collections.sort(List l)
for sorting elements in a vector.
I agree. Here's the link:
subject: Class Cast Exception - Please help
jQuery in Action, 3rd edition