Core Java - [Vector Class]

♠ Posted by Unknown in at 01:26

Vector class


The Vector class contained in the java.util package. This class can be used to create a generic dynamic array known as vector that can hold objects of any type and any number. The objects do not have to be homogenous. Arrays can be easily implemented as vectors. Vectors are created like arrays as follows:
                       
                        Vector intVect = new Vector(); //declaring without size
                        Vector list = new Vector(3); //declaring with size

The vector can be declared without specifying any size explicitly. A vector can accommodate an unknown number of items. Even, when a size is specified, this can be overlooked and a different number of items may be put into the vector. Remember, in contrast, an array must always have its size specified.

Vectors possess a number of advantages over arrays.
1.      It is convenient to use vectors to 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 list as and when required.

A major constraint in using vectors is that we cannot directly stores simple data types in a vector; we can only store objects.

list.addElement(item)

Adds the item specified to the list at the end

list.elementAt(10)

Gives the name of the 10th object

list.size()

Gives the number of objects present

list.removeElement(item)

Removes the specified item from the list

list.removeAllElements()

Removes the item stored in the nth position of the list

list.copyInto(array)

Copies all items from list to array

list.insertElementAt(item, n)

Inserts the item at nth position

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 Languages");

                                    for(int i = 0; i < size; i++)
                                    {
                                                System.out.println(listArray[i]);
                                    }
                        }
}

0 comments:

Post a Comment