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;
}
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.
If the only thing you want to do is to cast from Vector<Object> to Vector<String>, that you can do. You'll have to be sure every object in your vector is a String though!
Obviously, this won't work:
Vector<Object> objectVector = new Vector<Object>();
Vector<String> stringVector = (Vector<String>)objectVector;
But you can do this:
Vector<Object> objectVector = new Vector<Object>();
Vector typelessVector = objectVector;
Vector<String> stringVector = (Vector<String>)typelessVector;
You'll get some warnings, but the code should work fine.
As was mentioned before, this does feel like a code smell.
If you're definitely trying to create a new independent collection which contains a copy of N references, it's hard to see how that could possibly be O(1) without something like copy-on-write support.
Have you found this to actually be a performance bottleneck in your code? And is there any reason why you're using Vector
instead of ArrayList
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With