Methods in Vector Class

Collections Framework in Java has a Vector class. This Vector class has very useful methods, lets see some of the methods in Vector Class with examples.

Example-1:

Vector accepts an object like btn are accepted as object.

import java.util.Vector;
import javax.swing.JButton;
 
public class vector {
public static void main(String args[])   
{
    Vector vector=new Vector();
    vector.add("one");
    vector.add("two");
    vector.add("three");
    System.out.println(vector);
    JButton btn=new JButton("XYZ");
    vector.add(btn);
    for(int k=0;k<=vector.size();k++)    
    {
    System.out.println(vector.get(k));
    }
}
}
//Vector accepts object. like btn are accepted as object

Example-2:

Auto boxing converts primitives converted into objects.

import java.util.Vector;

public class vectorautoboxing {
    public static void main(String args[])
    {
    Vector vector=new Vector();
    vector.add(1);                      //auto boxing
    vector.add(2);                      //auto boxing
    System.out.println(vector);
}
}
//Auto boxing converts primitives converted into objects.

Example-3:

In this example, we make Vector to accept only Strings we can say we make it type safe. Now if we pass integer then the program will give compile time error.

import java.util.Vector;

public class vectortypesafe {
    public static void main(String args[])
    {
        Vector vectorstr=new Vector();
        vectorstr.add("one");
         vectorstr.add(1);
    }
}
/*here we make Vector to accept only Strings we can say we make it type safe. Now if we pass integer then the program will give compile time error.*/

OUTPUT:

type_safe

Example-4:

Downcasting Example

import java.util.Vector;
class a
{
    void abc()
    {
        System.out.println("abc.abc");
    }
}
class b
{
    void xyz()
    {
        System.out.println("xyz.xyz");
    }
}
public class classobject {
    public static void main(String args[])
    {  
        Vector vector =new Vector();
        a obja=new a();
        b objb=new b();
        vector.add(obja);
        vector.add(objb);
       
        a one;                      //variable “one” of class “a” type
        b two;                      //variable “two” of class “b” type
        one = (a)vector.get(0);     //down casting
        two = (b)vector.get(1);     //down casting
        one.abc();
        two.xyz();
    }
}

OUTPUT:

downcasting

Example-5:

Difference between type add and addElement method

import java.util.Vector;
public class accessvector {
 public static void main(String args[])  
 {
     Vector vector = new Vector();
     vector.add("krishna");
     vector.add("ram");                         // add method is not type safe
     vector.addElement("hanuman");              //addElement is type safe
     System.out.println(vector.get(1));
     //Object str=vector.get(2);
     System.out.println(vector.get(2));
 }
}

Example-6:

Accessing vector using foreach loop

package collection.list.vector;
import java.util.Vector;

public class vectorforeachloop {
    public static void main(String args[])
    {
        Vector vector =new Vector();
        vector.add("k");
        vector.add("v");
        vector.add("r");
        for (Object temp:vector)
        {
            System.out.println("plz. come  " +temp);
        }
    }
}

OUTPUT:

foreach

Example-9:

import java.util.Enumeration;
import java.util.Vector;
class employee1                              //constructor of employee class
{
int empid;
String name;
 employee1(int empid , String name)
{
    this.empid=empid;
    this.name=name;
}
void display()
{
    System.out.println("empid=" +empid +"\n" +"name=" +name);
}
}

public class vectorwithenum {
 public static void main(String args[])    
    {
        Vector vector =new Vector();
        vector.add(new employee1(7841,"abhi1"));                //making object of employee class with use defined constructor
        vector.add(new employee1(7441,"agg1"));                 //and adding it in Vector of employee type
        Enumeration e;                                          //”e” variable of emumeration type
        e=vector.elements();                                    //elements is a method in Vector whose value is stored in varable e
        while(e.hasMoreElements())
        {
            employee1 emp=(employee1)e.nextElement();
            emp.display();
        }
        
    }
}

//enumeration is used with vector
//enumeration is a kind of pointer which accesses all the elements or traverses all the elements.

OUTPUT:

empid=7841
name=abhi1
empid=7441
name=agg1

Example-11:

package collection.list.vector;

import java.util.Iterator;
import java.util.Vector;

public class vectorset {
    public static void main(String args[])
    {
        Vector vector=new Vector();
        vector.add("one");
        vector.add("two");
        vector.add("three");
        vector.add("four");
        System.out.println(vector.set(1,"apple"));
        Iterator itr=vector.iterator();
        while(itr.hasNext())
        {
            System.out.println(itr.next());
        }
    }
}

OUTPUT:

two
one
apple
three
four

//by the output it is observed that set method accept two parameters
// first is the location wherein the vector we have to insert them
//new object second parameter is the object and also set() return the
//object that is overwritten by the incoming object

Example-12:

package collection.list.vector;

import java.util.Iterator;
import java.util.Vector;

public class vectoranditsmethods {
    public static void main(String args[])
    {
        Vector vector= new Vector();
        vector.add(“one”);
        vector.add(“two”);
        vector.add(“three”);
        vector.add(“four”);
        System.out.println(vector.contains(“three”));   //return true if the Vector contains three, alse false
        System.out.println(vector.size());
        System.out.println(vector.capacity());
        System.out.println(“\n”);
        Vector vector2= new Vector();
        vector2.add(“1″);
        vector2.add(“2″);
        vector2.add(“3″);
        vector2.add(“4″);
        vector2.add(“5″);
        vector2.add(“6″);
        vector2.add(“7″);
        vector2.add(“8″);
        vector2.add(“9″);
        vector2.add(“10″);
        vector2.add(“one”);
        System.out.println(vector2.size());
        System.out.println(vector2.capacity());
        System.out.println(“\n”);
       vector.add(vector2);             // add() adds two vector
       //vector.addAll(vector2);
       Iterator itr=vector.iterator();
       while(itr.hasNext())
       {
           System.out.println(itr.next());
       }
       System.out.println(“\n”);
       vector.retainAll(vector2);       //retainAll() print common values.
       Iterator itr1=vector.iterator();
       while(itr1.hasNext())
       {
           System.out.println(itr1.next());
       }
      }
}

OUTPUT:

methods in vector

Example-13:

Difference between setElementAt and insertElementAt

package myvector;

import java.util.List;
import java.util.Vector;

public class VectorMethods {
    public static void main(String args[])
    {

    Vector vector=new Vector(10);
    vector.add("1");
    vector.add("2");
    vector.add("3");
    vector.add("4");
    System.out.println("capacity "+vector.capacity());

    /*
     * Trims the capacity of this vector to be the vector's current size. If the capacity of this vector is larger than its current size, then the capacity is changed to equal the size by replacing its internal data array, kept in the field elementData, with a smaller one. An application can use this operation to minimize the storage of a vector.
     */
    vector.trimToSize(); 
    System.out.println("capacity "+vector.capacity());
    System.out.println("Accessing particular index from vector\t"+vector.get(1));   //in Vector count starts from 0(zero)  

    System.out.println("Print vector element in form of string\t"+ vector.toString());  //return each element in the form of string

    System.out.println("Vector before inserting element\t"+vector);

    /*
     * Sets the component at the specified index of this vector to be the specified object. The previous component at that position is discarded
     */
     vector.setElementAt("5", 1); 
    System.out.println("Vector after inserting element using setElementAt() \t"+vector);

    /*
     * insert element at specified index and each component in this vector with an index greater or equal to the specified index is shifted upward to have an index one greater than the value it had previously.
     */
    vector.insertElementAt("4", 1); 
    System.out.println("Vector after inserting element using insertElementAt() \t"+vector);

    /*You can take the sublist out from the complete vector*/
    List list=vector.subList(1, 3);  //subList(startindex, endindex), return type is List
    System.out.println(""+list);

    }
}

OUTPUT:

vector_methods