Thursday, 19 May 2011

Operating on Vectors in java–Common Operations

To Create a Vector

You must import either import java.util.Vector; or import java.util.*;. Vectors are implemented with an array, and when that array is full and an additional element is added, a new array must be allocated. Because it takes time to create a bigger array and copy the elements from the old array to the new array, it is a little faster to create a Vector with a size that it will commonly be when full. Of course, if you knew the final size, you could simply use an array. However, for non-critical sections of code programmers typically don't specify an initial size.
  • Create a Vector with default initial size
    Vector v = new Vector();
  • Create a Vector with an initial size
    Vector v = new Vector(300);

 

 

To Add elements to the end of a Vector

v.add(s); // adds s to the end of the Vector v

No comments:

Post a Comment