Java2all.com  

Vector class





Share This Topic -

Vector class :

  • The Vector class is one of the most important in all of the Java class libraries. We cannot expand the size of a static array.
  • We may think of a vector as a dynamic array that automatically expands as more elements are added to it.
  •  All vectors are created with some initial capacity.
  • When space is needed to accommodate more elements, the capacity is automatically increased.
  • That is why vectors are commonly used in java programming.

This class provides the following constructors:

            Vector()

            Vector(int n)

            Vector(int n, int delta)

  • The first form creates a vector with an initial capacity of ten elements.
  •  The second form creates a vector with an initial capacity of n elements.
  • The third form creates a vector with an initial capacity of n elements that increases by delta elements each time it needs to expand. 

EX :

 import java.util.*;
public class Vector_Demo
{
	public static void main(String args[])
	{
		int i;
		Vector v = new Vector();
		v.addElement(new Integer(10));
		v.addElement(new Float(5.5f));
		v.addElement(new String("Hi"));
		v.addElement(new Long(2500));
		v.addElement(new Double(23.25));
		System.out.println(v);
		String s = new String("Bhagirath");
		v.insertElementAt(s,1);
		System.out.println(v);
		v.removeElementAt(2);
		System.out.println(v);
		for(i=0;i<5;i++)
		{
			System.out.println(v.elementAt(i));
		}
	}	
}

 
Output :
 
Bhagirath
Hi
2500
23.25