| written 9.7 years ago by | • modified 9.7 years ago |
Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology
Marks: 5 M
Year: Dec 2014
| written 9.7 years ago by | • modified 9.7 years ago |
Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology
Marks: 5 M
Year: Dec 2014
| written 9.7 years ago by |
The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.
Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector's storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.
Three ways to create vector class object:
Method 1:
Vector vec = new Vector();
It creates an empty Vector with the default initial capacity of 10. It means the Vector will be re-sized when the 11th elements needs to be inserted into the Vector. Note: By default vector doubles its size. i.e. In this case the Vector size would remain 10 till 10 insertions and once we try to insert the 11th element It would become 20 (double of default capacity 10).
Method 2:
Syntax: Vector object= new Vector(int initialCapacity)
Vector vec = new Vector(3);
It will create a Vector of initial capacity of 3.
Method 3:
Syntax:
Vector object= new vector(int initialcapacity, capacityIncrement)
Vector vec= new Vector(4, 6)
Here we have provided two arguments. The initial capacity is 4 and capacityIncrement is 6. It means upon insertion of 5th element the size would be 10 (4+6) and on 11th insertion it would be 16(10+6).
Example of Vector:
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
/* Vector of initial capacity(size) of 2 */
Vector<String> vec = new Vector<String>(2);
/* Adding elements to a vector*/
vec.addElement("Apple");
vec.addElement("Orange");
vec.addElement("Mango");
vec.addElement("Fig");
/* check size and capacityIncrement*/
System.out.println("Size is: "+vec.size());
System.out.println("Default capacity increment is: "+vec.capacity());
vec.addElement("fruit1");
vec.addElement("fruit2");
vec.addElement("fruit3");
/*size and capacityIncrement after two insertions*/
System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after increment is: "+vec.capacity());
/*Display Vector elements*/
Enumeration en = vec.elements();
System.out.println("\nElements are:");
while(en.hasMoreElements())
System.out.print(en.nextElement() + " ");
}
}