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.


PROGRAM
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(v.elementAt(i));
  }
  System.out.println(v);
  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(v);
  v.remove(4);
  System.out.println("After removing 4th element : "+v);
 }

}
OUTPUT
C:\>javac UsingVectorMethods.java
C:\>java UsingVectorMethods
10
2.5
8.5
A
ABC
[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]

Comments

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Program to input age from user and throw user-defined exception if entered age is negative

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.