Java – Vector class

Previous
Next

Vector :

  • Vector class is the implementation of List interface.
  • Vector class is available in java.util package.
  • Vector class in java api Since jdk 1.0
  • Vector class is Ordered
  • Vector class allows duplicates
  • Vector class initial capacity is n=10
  • Vector class capacity increments by doubled(2n)
  • Vector is synchronized by default.

Note: In ArrayList it is not possible to check the internal capacity(no such method). But in Vector we can check internal capacity and incrementing capacity using pre-defined method.

Tip : Only the collection classes which are from jdk 1.0 are synchronized by default. Most of the Collection classes are introduced from jdk 1.2 which are not synchronized by default but can be syncrhronized explicitly user pre-defined static functions available in Collections class

for example…..

Collections.synchronizedList();
Collections.synchronizedSet();
Collections.synchronizedMap();
Collections.synchronizedSortedSet();
Collections.synchronizedSortedMap();
/* public Enumeration<E> elements()
	Returns an enumeration of the components of this vector.

boolean hasMoreElements()
	Tests if this enumeration contains more elements.

Object nextElement()
	Returns the next element of this enumeration if this enumeration object  */

import java.util.Vector;
import java.util.Enumeration;
class VectorDemo
 {
	public static void main(String[] args) 
		{
		Vector v = new Vector();
		System.out.println("intial size : "+v.size());//returns number of elements
		System.out.println("intial capacity : "+v.capacity());
		for(int i=10 ; i<=100 ; i+=10)
		{
			v.add(new Integer(i)); 
		}
		System.out.println("after 10 insertions size : "+v.size());
		System.out.println("after 10 insertions capacity : "+v.capacity());

		v.add(110);
		System.out.println("after 11 insertions size : "+v.size());
		System.out.println("after 11 insertions capacity : "+v.capacity());

		Enumeration e = v.elements();
		while(e.hasMoreElements())
		{
			System.out.println(e.nextElement());
		}
	}
}
  • Vector has many constructors.
  • One of the constructors is used to create Vector object by specifying the initial capacity and incrementing capacity.
import java.util.Vector;
import java.util.Enumeration; //interface
class VectorDemo 
{
	public static void main(String[] args) 
	{
		Vector v = new Vector(3,2);
		System.out.println("initial capacity : "+v.capacity());
		v.add(10);
		v.add(20);
		v.add(30);
		v.add(40);
		System.out.println("after 4 insertions, capacity : "+v.capacity());

		Enumeration e = v.elements();
		System.out.println("Vector elements are : ");
		while(e.hasMoreElements())
		{
			System.out.println(e.nextElement());
		}
	}
}
Previous
Next

Add Comment

Courses Enquiry Form