Friday, 25 November 2016

Program Using 'Vector' class

The Vector class implements a growable array of objects. Like an array, it contains elements that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created. It has methods such as capacity( ), size( ), addElement( ), copyInto( ), contains( ), etc.

Here in this program we are providing vector elements from command line arguments and store them in a vector v using addElement( ) method as shown in program. After that we have copied all the vector elements in String array and display them on console. The Vector class is present in java.util package. The syntax for creating a vector is shown below:
 
// Creates a vector with initial size 10
Vector  <vector-name> = new  Vector();

OR

// Creates a vector with specified initial capacity.
Vector  <vector-name> = new  Vector(initialCapacity);

OR

// Creates a vector with specified initial capacity and capacity increment.
Vector  <vector-name> = new  Vector(initialCapacity,  capacityIncrement);


PROGRAM
import java.util.Vector;

public class VectorDemo2 {

 public static void main(String[] args) {
  
  Vector v = new Vector();
  
  // Adding elements to vector
  v.addElement(new Integer(10));
  v.addElement(new String("ABC"));
  v.addElement(new Float(34.4));
  
  int size = v.size();
  System.out.println("Vector size : "+size);
  System.out.println(v);
  //Removing element from vector
  v.removeElementAt(2);
  size = v.size();
  System.out.println("Vector size : "+size);
  System.out.println(v);
 }

}
OUTPUT
C:\>javac VectorDemo2.java
C:\>java VectorDemo2
Vector size : 3
[10, ABC, 34.4]
Vector size : 2
[10, ABC]

No comments:

Post a Comment