| written 9.5 years ago by | • modified 9.5 years ago |
Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology
Marks: 5 M
Year: May 2014
| written 9.5 years ago by | • modified 9.5 years ago |
Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology
Marks: 5 M
Year: May 2014
| written 9.5 years ago by |
It is similar to ArrayList, but with two differences:
1) Vector is synchronized
2) it contains many legacy methods that are not part of the collections framework.
These objects do not have to be homogenous. Capacity of the Vector can be increased automatically.
Vector class defines three different constructors:
Vector()
Vector(int size)
Vector(int size, int incr)
The first form creates a default vector, which has an initial size of 10.
The Vector class defines three protected data members:
int capacityIncrement;
int elementCount;
Object[] elementData;
Methods of Vector:
1) void addElement(Object element): The object specified by element is added to the vector.
2) int capacity() : It returns the capacity of the vector.
3) Object clone() : It returns a duplicate copy of the invoking vector.
4) boolean contains(Object element) : It returns true if ‘element’ is contained by the vector, and returns false if it is not.
5) int size() : It returns the number of elements currently in the vector
6) void insertElementAt(Object element, int index) : It adds ‘element’ to the vector at the location specified by ‘index’.
7) void removeElementAt(int index) : It removes the element at the location specified by ‘index’.
// Demonstrate various Vector operations.
import java.util.*;
class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(new Integer(1));
v.addElement(new Double(5.45));
v.addElement(new Integer(7));
v.addElement(new Float(9.4));
System.out.println("Current capacity: " + v.capacity());
System.out.println("First element: " + (Integer)v.firstElement());
System.out.println("Last element: " + (Float)v.lastElement());
if(v.contains(new Integer(7)))
System.out.println("Vector contains 7");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}