Vector class is in java.util package of java. Vector is dynamic array which can grow automatically according to the required need. Vector does not require any fix dimension like String array and int array. Vector contains many useful methods. To add element in Vector, we can use add() method of vector class. To add elements at fix position, we have to use add(index, object) method.
To get value from Vector, Vector provides get() method and Vector size() method. Size() method returns total number of elements in Vector.
Vector is synchronized, ArrayList is not
Vector Example
import java.util.Vector; public class VectorExample { public static void main(String[] args) { Vector<String> vc=new Vector<String>(); // <E> Element type of Vector e.g. String, Integer, Object ... // add vector elements vc.add("Vector Element 1"); vc.add("Vector Element 2"); vc.add("Vector Element 3"); vc.add("Vector Element 4"); vc.add("Vector Element 5"); // add vector element at index vc.add(3, "Element at fix position"); // vc.size() inform number of elements in Vector System.out.println("Vector Size :"+vc.size()); // get elements of Vector for(int i=0;i<vc.size();i++) { System.out.println("Vector Element "+i+" :"+vc.get(i)); } } }
Output
ArrayList Size :6
Vector Element 0 :Vector Object 1
Vector Element 1 :Vector Object 2
Vector Element 2 :Vector Object 3
Vector Element 3 :Element at fix position
Vector Element 4 :Vector Object 4
Vector Element 5 :Vector Object 5
Tags: Collections



Link to Us