Vector Class :
- The underlying data structure is a resizable array or growable array.
- Insertion order is preserved.
- Duplicates objects are allowed.
- Heterogeneous objects are allowed.
- Null insertion is possible.
- Vector implements Serializable, Cloneable interfaces and Random Access interfaces.
- Vector is the best choice if our frequent operation is retrieval.
- Linked List is the worst choice if our frequent operation is retrieval operation.
- Most of the methods in vector objects are Synchronized. Hence vector object is Thread-Safe.
Methods:
For add object:-
- add(Object o)
- add(int index, Object o)
- addElement(Object o)
For removing objects:-
- remove(Object o)
- removeElement(int index, Object o)
- remove(int index)
- removeElement(int index)
- clear()
- removeAllElements()
For retrieval elements:-
- Object get(int index)
- Object elementAt(int index)
- Object firstElement()
- Object LastElement()
For other methods:-
- int size() //Current Size
- int capacity(int index) // Total Capacity
- Enumeration elements() // Retrieve elements one by one
CONSTRUCTORS
- Vector V = new Vector();
- Creates an empty vector object with default initial capacity 10, Once Vector reaches its max capacity.
New Capacity = 2* Current Capacity
- Vector v = new Vector(int initialCapacity);
- Vector v = new Vector(int initialCapacity, int increamentalCapacity)
- Vector v = new Vector(Collection c );//creates an equivalent vector object for the given collection
Example of Vector :
import java.util.Vector; public class VectorDemo{ public static void main(String arg[]){ Vector v = new Vector(); System.out.println(v.capacity());//[10] for(int i=0; i<10; i++){ v.addElement(i); } System.out.println(v.capacity());//[10] v.addElement("A"); System.out.println(v.capacity());//[20] System.out.println(v); } }
Output :
10
10
20
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A]