Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

conversion from Vector to array

 
Humberto Hernandez
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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");
...
vec.add(elem);
}
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
Posts: 396
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI humberto,
String is a subclass of object - true .
so
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.
regards
Deekasha
 
Humberto Hernandez
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Humberto Hernandez
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. This is excactly what I was looking for.
 
Clara Zetkin
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic