import java.util.Enumeration;
import java.util.Vector;
class VectorTest
{
public static void main(String arg[])
{
// initial size is set to 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println(" size: " + v.size()); // sixe method
System.out.println("Initial capacity: " + v.capacity()); // capacity method
v.add(1); // add method
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " + v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " + v.firstElement()); // first element method
System.out.println("Last element: " + v.lastElement()); // last element method
if (v.contains(new Integer(3))) // contains method
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration e = v.elements(); // Enumeration
System.out.print("Elements in vector : ");
while (e.hasMoreElements())
System.out.print(e.nextElement() + " ");
}
}
size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector : 1 2 3 4 5.45 6.08 7 9.4 10 11 12
In this program, a Vector
constructor is taken where the initial size is set to 3
and the increment of size 2
for every additional element. The size of vector is 0
because no element in inserted and capacity is 3
i.e. initial size set is 3
. Four Integers
are added, now the capacity becomes 5
i.e. initial 3 + increment 2
, a double is added to vector the capacity remains same and again two elements are added then the capacity becomes 7
i.e. 5+2
, and again two elements are added so capacity becomes 9
and again two elements are added to the vector. The first and last elements are retrieved and the existence of 3
elements checked and then vector is assigned to Enumeration and printed the vector elements.
8
in to the vector at index 8
by using add(int index, Object element)
.clone, clear, elementAt
or get
and hashCode
methods to clone, clear, to get element at specified index and to get the hash code of the vector. equals, indexOf, isEmpty, lastIndexOf, remove, retain
and set
methods to vector.