• 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

Class Cast Exception - Please help

 
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic