Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently typecast elements of a vector in Java

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.

like image 780
Chris Redford Avatar asked Dec 12 '22 20:12

Chris Redford


2 Answers

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.

like image 96
Joeri Hendrickx Avatar answered Jan 01 '23 13:01

Joeri Hendrickx


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?

like image 43
Jon Skeet Avatar answered Jan 01 '23 13:01

Jon Skeet