Ad

Vector class

Vectors can be used to create a dynamic array that can hold objects of any type and any number. The objects do not have to be homogenous (same). Vector class contained in the java.util package.

Vector can be declared as follows:

Vector list = new vector(); //Declaring vector without size is known as explicit declaration.
Vector list = new vector(5); //Declaring vector with size is known as implicit declaration.

Advantages of Vector over Array:

  1. Vectors are convenient to use because it store objects.
  2. A Vector can be used to store a list of objects that may vary in size.
  3. We can add and delete objects from the vector list as when required.
Methods use in Vector:
  1. list.addElement(item): Add the item specified to the list at the end.
  2. list.elementAt(10): Gives the name of 10th object.
  3. list.size(): Gives the number of objects present.
  4. list.removeElement(item): Remove the specified item from the list.
  5. list.removeElementAt(n): Remove the item stored in nth position of the list.
  6. list.removeAllElements(): Removes all the elements in the list.
  7. list.copyInto(array): Copies all items from list to array.
  8. list.insertElementAt(item, n): Inserts the item at nth position.

Example 1: WAP to convert a string vector into an array of strings and displays the strings.

import java.util.*;
class languagevector
{
    public static void main(String args[])
    {
        Vector list = new Vector();
        int length = args.length;
        for(int i=0; i<length; i++)
        {
            list.addElement(args[i]);
        }
        list.insertElementAt("COBOL",2);
        int size = list.size();
        String listArray[] = new String[size];
        list.copyInto(listArray);
        System.out.println(“List of Language”);
        for(int i=0; i<size; i++)
        {
            System.out.println(listArray[i]);
        }
    }
}
javac languagevector.java
java languagevector ada basic cpp fortran java
List of Languages
Ada
Basic
Cobol
Cpp
Fortran
Java
Advertisement