my dog learned polymorphism
The moose likes Java in General and the fly likes conversion from Vector to array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "conversion from Vector to array" Watch "conversion from Vector to array" New topic

conversion from Vector to array

Humberto Hernandez

Joined: Nov 01, 2000
Posts: 13
This is a pattaern that I have found frecuently but I haven't found a satisfactory answer yet.
I want to create a method that returns an array of elements of some type.
String []getNames() {
Vector vec = new Vector();
while(some_condition) { // Do this and unkown number of times.
String elem = new String("asfasdfasdf");
return (String [])vec.toArray();
I have to use a Vector to add the elements since I don't know in advance the number of elements. But I want to return an array of String so I have to make the conversion. Eventhough, this compiles fine it throws a class cast exception. I think this should work since String[] inherits from Object[]. And every element in the Vector is a String. Can anyone expliain why this doesn�t work. Does any one know an easy way to make the conversion without having to do it element by element.

deekasha gunwant
Ranch Hand

Joined: May 06, 2000
Posts: 396
HI humberto,
String is a subclass of object - true .
u can assign a String to an Object but vice versa is not allowed.
On the same line youn cast an String[] to Object[] but not vice versa.
that explains the error.
Humberto Hernandez

Joined: Nov 01, 2000
Posts: 13
Thanks, I think I understand now. Vector.toArray() really returns an Object[] that cannot be casted to a String[].
Does anyone know an easy way to accomplish this. That is write a function that return a String[] if you don�t know how many elements the array will have before hand.
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
If you look at the specification for Vector, you will note that there is an alternative "toArray" which takes an Object[] as a parameter. If you wish, you can pass in a String[] "in disguise", as follows:

Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Humberto Hernandez

Joined: Nov 01, 2000
Posts: 13
Thank you. This is excactly what I was looking for.
Clara Zetkin

Joined: Dec 10, 2002
Posts: 19
I've got a related problem, but my Vector contains Arrays (which contain Strings). So
String[][]ret = new String[ rows.size() ][numberOfColumns];
ret = (String [][])rows.toArray(ret);
will give me an ArrayStoreException, can anyone help?
I agree. Here's the link:
subject: conversion from Vector to array
It's not a secret anymore!