/* related posts with thumb nails */

Vectors:

Vector class is 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 homogeneous. Arrays can be easily implemented as vectors. The variable-arguments feature can also be achieved in Java through the use of the Vector. Vectors are created like arrays as follows:

Vector list = new Vector ( ); // declaring without size

Vector list = new Vector (3); // declaring with size

A vector can be declared without specifying any size explicitly. A vector without size 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. But, in contrast, an array must always have its size specified.

Vectors have a number of advantages over arrays.

· It is convenient to use vectors to store objects.

· A vector can be used to store a list of objects that may vary in size.

· We can add and delete objects from the list as and when required.

A major constraint in using vectors is that we cannot directly store simple data type in a vector; we can only store objects. Therefore, we need to convert simple types to objects. This can be done using the wrapper classes. The vector class supports a number of methods that can be used to manipulate the vectors created.

addElement(item)

Adds the item specified to the list at the end

elementAt(n)

Gives the name of the nth object

slze()

Gives the number of objects present

removeElement(item)

Removes the specified item from the list

removeElementAt(n)

Removes the item stored in the nth position of the list

removeAllElements( )

Removes all the elements in the list

copyInto(array)

Copies all items from list to array

InsertElementAt (Item, n)

Inserts the item at nth position

Example: The following program demonstrates Vector and some of its methods.

import java.util.*;

class VectorTest

{

public static void main(String as[])

{

Vector v1=new Vector(10);

v1.add(“Apple”);

v1.add(“Banana”);

v1.add(“Mango”);

v1.insertElement(“Sapota”,2);

v1.removeElementAt(3);

System.out.println("Number of Elements:"+v.size());

System.out.println("Vector Elements:"+v1);

}

}

/* Output: */

Number of Elements: 3

Vector Elements: [Apple, Banana, Sapota]

Related Topics:

0 comments:

Post a Comment