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 Object 1"); vc.add("Vector Object 2"); vc.add("Vector Object 3"); vc.add("Vector Object 4"); vc.add("Vector Object 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)); } } }
Tags: Collections





Link to Us
There’s a bug: why You write “System.out.println(”Vector Size :”+vc.size());” and then the output is “ArrayList Size :6″???
Sound me something wrong :S
Vector progam is working fine when i checked, 6 times vector added so printing 6, tell us the bug in detail
The problem is that you inserted the elements as the following strings:
vc.add(”Vector Element #”);
and you printed them out with vc.get(i) which led to them being the following strings:
Vector Object #
You example would have been clearer if you inserted them as “Vector Object #”