Demonstrate use of 'Vector' class methods

In this program, we have used the following methods of a Vector class:
  1. size( ) : It returns the number of elements present in the vector.
  2. elementAt(int index) :It returns the element at the specified index.
  3. capacity( ) : It returns the current capacity of the vector.
  4. indexOf(Object o) : It returns the index of the first occurrence of the specified element in the vector, or -1 if this vector does not contain the element.
  5. firstElement( ) : It returns the first element (the item at index 0) of this vector.
  6. lastElement( ) : It returns the last element of the vector.
  7. insertElementAt(E obj, int index) : Inserts the specified object as a element in the vector at the specified index.
  8. remove(int index) : Removes the element at the specified position in the Vector.
  9. remove(Object o) : Removes the first occurrence of the specified element in the Vector. If the Vector does not contain the element, it is unchanged.

import java.util.Vector;

public class UsingVectorMethods {

 public static void main(String[] args) {
  Vector v = new Vector();
  v.addElement(new Integer(10));
  v.addElement(new Float(2.5));
  v.addElement(new Double(8.5));
  v.addElement(new Character('A'));
  v.addElement(new String("ABC"));
  int s = v.size();
  for(int i=0; i<s; i++)
  System.out.println("Size = "+s);
  System.out.println("Capacity = "+v.capacity());
  System.out.println("Index of ABC= "+v.indexOf("ABC"));
  System.out.println("First element= "+v.firstElement());
  System.out.println("Last element= "+v.lastElement());
  v.insertElementAt(new Boolean(true),3);
  System.out.println("After removing 4th element : "+v);

C:\>java UsingVectorMethods
[10, 2.5, 8.5, A, ABC]
Size = 5
Capacity = 10
Index of ABC= 4
First element= 10
Last element= ABC
[10, 2.5, 8.5, true, A, ABC]
After removing 4th element : [10, 2.5, 8.5, true, ABC]

No comments:

Post a comment