Friday, June 17, 2016

Vector Class example java

Vector Class

A vector also stores elements similar to ArrayList, but Vector is synchronized.It means if several threads act on same vector object simultaneously,the result will be reliable.

Default Capacity=10
Load Factor=0.75

Vector Class Methods

  • boolean add(element obj)
  • void add(int position,element obj)
  • element remove(int position)
  • boolean remove(Object obj)
  • void clear()
  • element set(int position,Object obj)

  • boolean contains(Object obj)
  • element get(int position)
  • int indexOf(Object obj)
  • int lastIndexOf(Object obj)
  • int size()
  • int capacity()
Program:


/**
 * 
 */
package com.collectionpack;

import java.util.ListIterator;
import java.util.Vector;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class VectorDemo
{

/**
* @param args
*/
public static void main(String[] args)
{
Vector<Integer> vector=new Vector<Integer>();
int x[]={22,10,40,15,60};
for(int i=0;i<x.length;i++)
{
vector.add(x[i]);
}

System.out.println("Vetcor elements:");
for(int  j=0;j<vector.size();j++)
{
System.out.println(vector.get(j));
}
System.out.println("Elements using ListIterator....");
ListIterator lite=vector.listIterator();
System.out.println(("In forward Direction"));
while(lite.hasNext())
{
System.out.println(lite.next() + "\t");
}
System.out.println("In backward direction");
while(lite.hasPrevious())
{
System.out.println(lite.hasPrevious() + "\t");
}
}

}

What is the difference between ArrayList and Vector?
Ans:
ArrayList                                                                                                     Vector

1. ArrayList Object is not Synchronized.    1.Vector Object is synchronized by default.

2. ArrayList is faster in single threaded-       2.In case of Multi-Threads,vector is advisable but           
                                                                           becomes slow in case of single Thread.
-mode.

3.It increases it size by 50% half of its size.  3.It increases its size by doubling it.

Can you synchronize the ArrayList object?

Ans: Yes,we can use synchronizedList() method to synchronize the ArrayList.

          Collections.synchronizedList(new ArrayList());


No comments: