Skip to Content

Get Size of Java Vector and loop through the elements Example

  1. /*
  2.   Get Size of Java Vector and loop through the elements Example
  3.   This Java Example shows how to get size or number of elements currently
  4.   stored in Vector. It also shows how to loop through the element of it.
  5. */
  6.  
  7. import java.util.Vector;
  8.  
  9. public class GetSizeOfVectorExample {
  10.  
  11.   public static void main(String[] args) {
  12.     //create a Vector object
  13.     Vector v = new Vector();
  14.    
  15.     //Add elements to Vector using
  16.     v.add("1");
  17.     v.add("2");
  18.     v.add("3");
  19.  
  20.     //To get size of Java Vector use int size() method
  21.     int totalElements = v.size();
  22.    
  23.     System.out.println("Vector contains...");
  24.     //loop through it
  25.     for(int index=0; index < totalElements; index++)
  26.       System.out.println(v.get(index));
  27.    
  28.   }
  29. }
  30.  
  31. /*
  32. Output would be
  33. Vector contains...
  34. 1
  35. 2
  36. 3
  37. */