Skip to Content

Simple Java Vector Example

  1. /*
  2.   Simple Java Vector Example
  3.   This Java Example shows how to create an object of Java Vector. It also
  4.   shows how to add elements to Vector and how get the same from Vector.
  5. */
  6.  
  7. import java.util.Iterator;
  8. import java.util.Vector;
  9.  
  10. public class SimpleVectorExample {
  11.  
  12.   public static void main(String[] args) {
  13.    
  14.     //create a Vector object
  15.     Vector v = new Vector();
  16.    
  17.     /*
  18.        Add elements to Vector using
  19.        boolean add(Object o) method. It returns true as a general behavior
  20.        of Collection.add method. The specified object is appended at the end
  21.        of the Vector.
  22.     */
  23.     v.add("1");
  24.     v.add("2");
  25.     v.add("3");
  26.    
  27.     /*
  28.       Use get method of Java Vector class to display elements of Vector.
  29.       Object get(int index) returns an element at the specified index in
  30.       the Vector    
  31.     */
  32.     System.out.println("Getting elements of Vector");
  33.     System.out.println(v.get(0));
  34.     System.out.println(v.get(1));
  35.     System.out.println(v.get(2));
  36.   }
  37. }
  38.  
  39. /*
  40. Output would be
  41. Getting elements of Vector
  42. 1
  43. 2
  44. 3
  45. */