Google News
logo
Java Vector class
Vector
1) Introduced in 1.0 v legacy classes.
2) Duplicate objects are allowed
3) Null insertion is possible
4) Heterogeneous objects are allowed
5) The under laying data structure is growable array.
6) Insertion order is preserved.
7) Every method present in the Vector is synchronized and hence vector object is Thread safe.
Creating Vector object
We can create a Vector objects in many different ways as shown below: 

1) Vector v = new Vector();
The preceding statement creates a Vector object v which can be used to store Float type objects. The default capacity will be 10. 

2)Vector v = new Vector(200);
The preceding statement creates a Vector object v which can be used to store Integer type objects. The capacity of Vector is given as 200. Another way of creating an object for Vector is by specifying a capacity increment which specifies how much the capacity should be incremented when the Vector is full with elements. 

3)Vector v = new Vector(200, 50);
Here, 200 is the capacity of the Vector and capacity increment is 50. If the Vector is full with elements; the capacity automatically goes to 250.
Important methods of Vector Class:
1.void addElement(Object element): It inserts the element at the end of the Vector. 

2.int capacity(): This method returns the current capacity of the vector. 

3.int size(): It returns the current size of the vector.
 
4.void setSize(int size): It changes the existing size with the specified size. 

5.boolean contains(Object element): This method checks whether the specified element is present in the Vector. If the element is been found it returns true else false. 

6.boolean containsAll(Collection c): It returns true if all the elements of collection c are present in the Vector. 

7.Object elementAt(int index): It returns the element present at the specified location in Vector. 

8.Object firstElement(): It is used for getting the first element of the vector. 

9.Object lastElement(): Returns the last element of the array. 

10.Object get(int index): Returns the element at the specified index. 

11.boolean isEmpty(): This method returns true if Vector doesn't have any element. 

12.boolean removeElement(Object element): Removes the specifed element from vector. 

13.boolean removeAll(Collection c): It Removes all those elements from vector which are present in the Collection c. 

14.void setElementAt(Object element, int index): It updates the element of specifed index with the given element.
Vector program
import java.util.*; 
class Test 
{ 
public static void main(String[] args) 
{ 
Vector v=new Vector(); 
for (int i=0;i<10 ;i++ ) 
{ 
v.addElement(i); 
} 
System.out.println(v); 
System.out.println(v); 
v.removeElement(0); 
System.out.println(v); 
v.clear(); 
System.out.println(v); 
} 
}
Output :
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[]