File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Class Cast Exception - Please help

 
Kishan Kumar
Ranch Hand
Posts: 130
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Christopher Gregory
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 130
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic