Thursday, December 28, 2017

Vector in Java


Vector also implements List interface. So its also having same feature as ArrayList having like
underline data structure is re sizable array.  below are the same features which are followed.

1. insertion order is preserved.
2. duplicates are allowed.
3. heterogeneous objects are allowed.
4. null insertion is possible
5. Its implements serializable , clonable  and RandomAccess interfaces.

but one point to need to remember which is different from others every methods which are in the vector are synchronized So we can say vector objects are thread safe.

Vector Constructors :

 1. Vector v=new Vector();

as above creates empty vector object which is having default initial capacity 10.

once vector reaches its max capacity then a new vector object will be created with new capacity.

  new capacity= current capacity*2.

as above new capacity will be twice of current capacity.
if current capacity is 10 then new object capacity will be 20.

2. Vector v1=new Vector(int initial capacity);

creates an empty vector objects with specified initial capacity.
Vector v1= new Vector(100);

3. Vector v3=new Vector(int initial capacity, int increment capacity );
 Vector v3 new Vector(100, 5);

as above define vector object v3 which is having initial capacity 100  which will be incremented by 5.

4. Vector v4-new Vector(Collection c);
creates an equivalent object of Vector for the given collection object. this constructor means inter conversion.


Vector Specific Methods:

to add methods:
 1. addElement(object o) // Vector method
 2. add(object o) // Collection method
 3. add(int index, object o) // List

to remove methods:
 1.  remove(object o) // Collection method
 2. removeElement(object o) // Vector method
 3. remove(object o)    // List
 4. clear() // Collection
 5. removeAllElement() // Vector
to get methods:

 1. object get (int index) // LIst
 2. object elementAt(int index) //  Vector
 3. objet firstElement() // vector
 4. objet lastElement() // vector

other methods:

 1. int size();
2. int capacity();
3. Enumeration elements();



as below example we can use above methods and constructors.

package indrajeet.list.exp;

import java.util.Enumeration;
import java.util.Vector;

public class VectorExp {

public static void main(String[] args) {


Vector v=new Vector<>();
System.out.println(v.capacity()); //10
v.add("indraeet");
v.addElement("singh");
v.add(1, 4);
System.out.println(v); //[indraeet, 4, singh]
v.removeElementAt(1);

System.out.println(v);  //[indraeet, singh]
System.out.println(v.size()); //2

Enumeration e=v.elements();
while(e.hasMoreElements())
{
System.out.println( e.nextElement());
}

}

}

No comments: