title: Efficiently typecast elements of a vector in Java
body: <p>Is there a more efficient way (preferably O(1) rather than O(n) but <strong>at least faster to type</strong>) to typecast the elements of a vector than this?</p>
  
  <pre><code>public Vector&lt;String&gt; typecastVector(Vector&lt;Object&gt; objects){
      Vector&lt;String&gt; strings = new Vector&lt;String&gt;();
      for(Object o : objects)
          strings.add((String) o);
      return strings;
  }
  </code></pre>
  
  <h1>Note</h1>
  
  <p>To anyone who is running into an apparent need to typecast a <code>Vector</code> or other Generic class: as the accepted answerer points out, this is probably a <a href="http://en.wikipedia.org/wiki/Code_smell" rel="nofollow noreferrer">code smell</a> and you probably need to <a href="http://en.wikipedia.org/wiki/Code_refactoring" rel="nofollow noreferrer">refactor</a> the code in your class hierarchy.</p>
  
  <p><strong>Specifically</strong>, if you haven't already, you should consider making the classes that use said <code>Vector</code> or other Generic class use <a href="http://download.oracle.com/javase/tutorial/java/generics/index.html" rel="nofollow noreferrer">Generics</a> 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. </p>
  
  <p>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 <code>Vector</code> typecast.</p>