Basic Vector Operations

Below example shows how to create vector object, adding elements to it, getting elements by specifying index, getting elements index, getting first element, getting last element, and is vector is empty or not.

package pack1;

import java.util.Vector;

public class VectorBasicOperations {
  public static void main(String a[]){
    Vector<String> vct = new Vector<String>();
    //adding elements to the end
    vct.add("India");
    vct.add("Australia");
    vct.add("New Zealand");
    System.out.println(vct);
    //adding element at specified index
    vct.add(2,"Africa");
    System.out.println(vct);
    //getting elements by index
    System.out.println("Element at index 3 is: "+vct.get(3));
    //getting first element
    System.out.println("The first element of this vector is: "+vct.firstElement());
    //getting last element
    System.out.println("The last element of this vector is: "+vct.lastElement());
    //how to check vector is empty or not
    System.out.println("Is this vector empty? "+vct.isEmpty());
  }
}

Output:

[India, Australia, New Zealand]
[India, Australia, Africa, New Zealand]
Element at index 3 is: New Zealand
The first element of this vector is: India
The last element of this vector is: New Zealand
Is this vector empty? false

The only business I know is learning new technology and spreading the knowledge. I believe sharing is learning. This is my prime reason to build this site.
I welcome and value your comments, suggestions and corrections.

206total visits,10visits today

The only business I know is learning new technology and spreading the knowledge. I believe sharing is learning. This is my prime reason to build this site. I welcome and value your comments, suggestions and corrections.