permaculture playing cards*
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Class Cast Exception - Please help" Watch "Class Cast Exception - Please help" New topic
Author

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.

------------------
Regards,
V. Kishan Kumar


Regards,<BR>V. Kishan Kumar
Christopher Gregory
Greenhorn

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 array.....here's an example:
class VectorTest {

public static void main(String [] args) {

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

System.out.println(strArray[i]);
}
}
the output should be:
First
Second
Third
Hope this helps!
Kishan Kumar
Ranch Hand

Joined: Sep 26, 2000
Posts: 130
Christopher,
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Class Cast Exception - Please help
 
Similar Threads
Casting Object[] into String[]
Verifying element types of a Vector
How is priority determined?-Collection Doubt
conversion from Vector to array