MY mENU


Monday 9 April 2012

Vector in Collections


Vector: - It is a dynamically growing array that stores objects. But it is synchronized. When the object is synchronized then we will get reliable results or values. Vectors are suitable objects.


1. To create a vector
Vector v = new Vector();
Vector v = new Vector (100);


2. To know the size of Vector, use size() method.
int n = v.size();


3. To add elements use add() method.
             v.add(obj);
             v.add(2, obj);


4. To retrieve elements use get() method
                      v.get(2);


5. To remove elements use remove() method
                   v.remove(2);
To remove all elements
                   v.clear();


6. To know the current capacity, use capacity() method
                 int n = v.capacity();


7. To search for last occurrence of an element use indexOf() method
              int n = v . intdexOf(obj);


8. To search for last occurrence of an element use lastIndexOf() method
               int n = v . lastIndexOf(obj);


9. Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.
void ensureCapacity(int minCapacity);


ArrayList is not synchronized by default, but by using some methods we can synchronized the ArrayList.


List myList = Collections.synchronizedList(myList);


Vector is synchronized default.  When we are retreiveing the elements from Vector, it will maintains and gives the same order what we have added the elements to the Vector.  Vector doesn’t supports the null values.


Ex: - //A Vector of int values


import java.util.*;
class VectorDemo
{
public static void main(String args[ ])
{
//Create an empty Vector
Vector v = new Vector ();
//Take (an one dimensional) int type array
int x [ ] = {10, 22, 33, 44, 60, 100};
//Read int values from x and store into v
for(int i = 0; i< x.lenght(); i++)
v.add(new Integer(x[ i ]));
//Retrieve and display the elements
for(int i = 0; i< v.size(); i++)
System.out.println(v.get(i));
//Retrieve elements using ListIterator
ListIterator lit = v. listIterator();
//QIn the above statement ListIterator is an Interface, listIterator() is a method
System.out.println(“In forward direction: ” );
while(lit.hasNext())
System.out.print (lit.next() +“\t”);
System.out.println (“\n In reverse direction: ”);
while(lit.previous())
System.out.print(lit.previous() + “\t”);
}
}

No comments:

Post a Comment