Skip to Content

Set size of Java Vector Example

  1. /*
  2.   Set size of Java Vector Example
  3.   This Java Example shows how to set the size of Java Vector object using
  4.   setSize method. Size of the Vector can be changed anytime after creating it using
  5.   this method.
  6. */
  7.  
  8. import java.util.Vector;
  9.  
  10. public class SetSizeOfJavaVectorExample {
  11.  
  12.   public static void main(String[] args) {
  13.     //create a Vector object
  14.     Vector v = new Vector();
  15.    
  16.     //Add elements to Vector
  17.     v.add("1");
  18.     v.add("2");
  19.     v.add("3");
  20.     v.add("4");
  21.     v.add("5");
  22.    
  23.     /*
  24.       To set the size of Vector use
  25.       void setSize(int newSize) method.
  26.       Please note that if the newSize is less than the current size of the Vector
  27.       elements at and after newSize index will be discarded, and if the newSize is
  28.       grater than the current size of Vector, null values are added at the end of
  29.       the Vector.
  30.     */
  31.     //set size of Vector to 3. The Last 2 elements would be discarded.
  32.     v.setSize(3);
  33.    
  34.     //display elements of the Vector
  35.     System.out.println("Vector elements after setting size to 3");
  36.     for(int index=0; index < v.size(); index++)
  37.       System.out.println(v.get(index));
  38.    
  39.     //set size of Vector to 5. null values would be inserted in the Vector.
  40.     v.setSize(5);
  41.  
  42.     //display elements of the Vector
  43.     System.out.println("Vector elements after setting size to 5");
  44.     for(int index=0; index < v.size(); index++)
  45.       System.out.println(v.get(index));
  46.    
  47.   }
  48. }
  49. /*
  50. Output would be
  51. Vector elements after setting size to 3
  52. 1
  53. 2
  54. 3
  55. Vector elements after setting size to 5
  56. 1
  57. 2
  58. 3
  59. null
  60. null
  61. */