Home‎ > ‎Applied Core Java‎ > ‎Collection Framework‎ > ‎

TestVector

Problem : Create a dynamic vector that can add any number of elements of any object. 

Program :

Step 1 - Coding

Create a text file c:\sunilos\TestVector.java  and copy below contents.

import java.util.*;

/*
 * A program to implement Vector.
 */


public class TestVector {

    public static void main(String[] args) {

        Vector v  = new Vector();
        // You can insert any object in the Vector. Here it is string

        v.add("Jay");
        v.add("Viru");
        v.add("Basanti");

        // Return type of get() method is Object.

        Object o = v.get(0);

        /* You can insert any object in the Vector. Here it is Integer
         * Primitive data type need to be converted into Objects before
         * inserting.
                  */
        Integer i = new Integer(5);
        v.add(i);

        // Type cast your object in desired Class
        Integer value = (Integer) v.get(3);
        System.out.println("Value of Index # 3 = " + value);

        // Get all elements and print

        System.out.println("Print All Elements with help of For loop ");

        for (int j = 0; j < v.size(); j++) {
            System.out.println(j + " : " + v.get(j));
        }

        // Get all elements and print with help of Iterator interface
        Iterator it = v.iterator(); // Get an iterator

        System.out.println("Print All Elements with help of Iterator ");

        while (it.hasNext()) { // Checks if any element in list
            Object oo = it.next(); // Get next available element
            System.out.println(" From Iterator -- " + oo);
        }

        // Get all elements and print with help of Enumeration interface
        Enumeration e = v.elements(); // Get java.util.Enumeration objects

        System.out.println("Print All Elements with help of Enumeration ");

        while (e.hasMoreElements()) { // Checks if any element in list
            Object oo = e.nextElement(); // Get next available element
            System.out.println(" From Enumeration -- " + oo);
        }

    }

}

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy TestVector.java  into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile TestVector.java with help of 
    • javac TestVector.java command. Compiled class file will be created in the same folder
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of 
    • java TestVector command.

Output

C:\sunilos>java TestVector

Value of Index # 3 = 5

Print All Elements with help of For loop
0 : Jay
1 : Viru
2 : Basanti
3 : 5

Print All Elements with help of Iterator
 From Iterator -- Jay
 From Iterator -- Viru
 From Iterator -- Basanti
 From Iterator -- 5

Print All Elements with help of Enumeration
 From Enumeration -- Jay
 From Enumeration -- Viru
 From Enumeration -- Basanti
 From Enumeration -- 5

FAQ

What is Vector?

The Vector class is a dynamic growable array of objects. Elements can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.

As of the Java 2 platform v1.2, this class has been retrofitted to implement List, so that it becomes a part of Java's collection framework. Vector is synchronized.

Vector can be instantiated with some initial capacity and increment value.

Vector(int initialCapacity)
          Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero.
Vector(int initialCapacity, int capacityIncrement)
          Constructs an empty vector with the specified initial capacity and capacity increment.


What is difference between ArrayList and Vector?

 # ArrayList Vector
 1 Not Thread Safe
 Thread Safe
 2 Asynchronous
 Synchronous
 3 Vector is structurally modified at any time after the Iterator is created, in any way except through the Iterator's own remove or add methods, the Iterator will throw a ConcurrentModificationException.

What is an Iterator?

Iterator is used to read data sequentially from collection classes (Vector, ArrayList, TreeSet, etc.). Collection interface contains iterator() method that returns Iterator object.

What is Enumeration?

Just like iteration, it reads data sequentially from collection objects.

What are differences between Enumeration and Iterator?

An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework.
Iterators differ from enumerations in two ways:

                                                               i.      Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.

                                                             ii.      Method names have been improved.


In other words Iterator can remove an element whereas Enumeration can not.

Most Interesting methods in Vector?

  • add() - Inserts the specified element at the specified position in this Vector.
  • addElement() - Adds the specified component to the end of this vector, increasing its size by one.
  • clear() - Removes all of the elements from this Vector.
  • elementAt() - Returns the component at the specified index.
  • elements() - Returns an enumeration of the components of this vector.
  • equals() - Compares the specified Object with this Vector for equality.
  • firstElement() - Returns the first component (the item at index 0) of this vector.
  • get() - Returns the element at the specified position in this Vector.
  • hashCode() - Returns the hash code value for this Vector.
  • indexOf() - Searches for the first occurence of the given argument, testing for equality using the equals method.
  • insertElementAt() - Inserts the specified object as a component in this vector at the specified index.
<<Previous | Next>>
ċ
TestVector.java
(2k)
Mahima Hardia,
Aug 19, 2011, 11:12 PM
Comments