Is there a more efficient way (preferably O(1) rather than O(n) but at least faster to type) to typecast the elements of a vector than this?
public Vector<String> typecastVector(Vector<Object> objects){
Vector<String> strings = new Vector<String>();
for(Object o : objects)
strings.add((String) o);
return strings;
}
Note
To anyone who is running into an apparent need to typecast a Vector
or other Generic class: as the accepted answerer points out, this is probably a code smell and you probably need to refactor the code in your class hierarchy.
Specifically, if you haven't already, you should consider making the classes that use said Vector
or other Generic class use Generics themselves. When I did this in my own code, I completely eliminated the need for the function in my code that was analogous to the above function.
If you've never implemented Generics in your own code, check the "Generics" link above. You may be surprised (as I was) to find that they can be used to implement precisely the functionality you thought you needed from a Vector
typecast.