- The underlying data structure for the vector is resizable array or grow able array.
- Duplicates objects are allowed.
- Insertion order is preserved.
- Null insertion is possible.
- Heterogeneous objects are allowed.
- Vector class implemented Serializable, Cloneable and RandomAccess.
- Most of the methods present in vector are synchronized. Hence vector object is thread safe.
- Best choice if frequent operation is retrieved.
Methods of vector class
For adding objects:-
add(Object o) [from Collection-List l]
add() [from List]
addElement(Object o) [from Vector]
For removing objects:-
remove(Object o) [from Collection]
removeElement(Object o) [from Vector]
remove(int index) [from List]
removeElementAt(int index) [from Vector]
clear() [from Collection]
removeAllElements() [from Vector]
=
For accessing elements:-
Object get(int index) [from Collection]
Object elementAt(int index) [from Vector]
Object firstElement() [from Vector]
Object lastElement() [from Vector]
Other Methods:-
int Size();
int Capacity();
Enumeration elements ();
Constructors of Vector class
Vector v = new Vector();
Creates an empty vector object with default
initial capacity 10, once vector reaches its maximum capacity a new object will
be created with new capacity.
New Capacity = 2*Current Capacity
Vector v = new Vector(int initial capacity);
Creates an empty vector object with specified initial capacity.
Vector v = new Vector(int initial capacity, int incremental capacity)
Vector v = new Vector(Collection c);
Creates an equivalent vector object for the given collection.
Example
package List;
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
Vector v = new Vector();
System.out.println(v.capacity()); // 10
for (int i = 1; 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); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A]
}
}
311 total views, no views today