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

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);
  //Removing element from vector
  size = v.size();
  System.out.println("Vector size : "+size);

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

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative