Menu
Topics Index
...
`

VectorMethodsDemo - Java Example Program


VectorMethodsDemo
import java.util.*;

class VectorMethodsDemo
{
    public static void main(String arg[])
    {
        Vector<Integer> numbers = new Vector<Integer>();
        numbers.add(new Integer(1));
        numbers.add(new Integer(2));
        numbers.add(new Integer(3));
        numbers.add(new Integer(5));
        numbers.add(new Integer(6));
        System.out.println("Vector Elements : " + numbers); // LINE A
        System.out.println("Vector contains 3 : " + numbers.contains(new Integer(3))); // LINE B
        System.out.println("Vector contains 4 : " + numbers.contains(new Integer(4))); // LINE C
        ArrayList al = new ArrayList(); // LINE D
        al.add(3);
        al.add(5);
        System.out.println("numbers contains all elements of al : " +  numbers.containsAll(al));    // LINE E
        System.out.println("Index value of 3 is : " + numbers.indexOf(3));    // LINE F
        numbers.add(new Integer(4)); // 4 will be added at the end of the stack
        numbers.remove(new Integer(6));    // LINE G
        System.out.println("Modified Vector: " + numbers);
        numbers.clear();    // LINE H
        System.out.println("Vector Elements after clear method : " + numbers);    
    }
}
OUTPUT

Vector Elements : [1, 2, 3, 5, 6]
Vector contains 3 : true
Vector contains 4 : false
numbers contains all elements of al : true
Index value of 3 is : 2
Modified Vector: [1, 2, 3, 5, 4]
Vector Elements after clear method : []

DESCRIPTION

In the above program, At LINE A we are printing all the elements in the stack. At LINE B contains method is used to find 3 in the stack, the output is true, since 3 is present in the stack. But at LINE C the output is false, since 4 is not present in the stack. At LINE D empty ArrayList is created and elements are add to the list. At LINE E we are checking wheter all the elements al are present in the numbers Vector. At LINE F we are finding the index value of 3 using IndexOf method. At LINE G we are removing 6 from numbers using remove method. At LINE H we are clearing all the elements in the vector by using clear method.

THINGS TO TRY
  • Insert the below line of code above LINE A and see the output.
    numbers.insertElementAt(new Integer(3), 3);
    The output for the above line of code is :
    Vector Elements : [1, 2, 3, 3, 5, 6]
    Here the insertElementAt method inserts the specified object in the specified field.
  • Insert the below line of code after LINE E.
    numbers.removeAll(al);
    System.out.println("The modified Vector is : " + numbers);
    The output for the above code is :
    The modified Vector is : [1, 2, 6]
    Here, numbers.removeAll method removes all the elements of al from the vector numbers.

© meritcampus 2019

All Rights Reserved.

Open In App