8.3 The Vector class 

Previous Index Next 


The Vector class implements a dynamic array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate the adding and removing of items after the Vector has been created.

The following piece of code demonstrates how to use a Vector object.

Vector aList = new Vector();
 
aList.addElement("Hello");
aList.addElement("There");
aList.addElement("This");
aList.addElement("Is a Test");

for (int loop=0; loop < aList.size(); loop++)
  System.out.println( (String) aList.elementAt(loop) ); // note type cast
The addElement() accepts a Object class. The size() method returns the number of elements that are in the list. The elementAt() method returns the element at the specified position in the Vector the element is returned as a Object so you need to type cast it to the correct type.
 



Source: 1