Programming Tutorials

Vector example in Java

By: Grenfel in Java Tutorials on 2007-09-14  

Vector implements a dynamic array. It is similar to ArrayList, but with two differences: Vector is synchronized, and it contains many legacy methods that are not part of the collections framework. With the release of Java 2, Vector was reengineered to extend AbstractList and implement the List interface, so it now is fully compatible with collections.

Here are the Vector constructors:

Vector()
Vector(int size)
Vector(int size, int incr)
Vector(Collection c)

The first form creates a default vector, which has an initial size of 10. The second form creates a vector whose initial capacity is specified by size. The third form creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward. The fourth form creates a vector that contains the elements of collection c. This constructor was added by Java 2.

All vectors start with an initial capacity. After this initial capacity is reached, the next time that you attempt to store an object in the vector, the vector automatically allocates space for that object plus extra room for additional objects. By allocating more than just the required memory, the vector reduces the number of allocations that must take place. This reduction is important, because allocations are costly in terms of time. The amount of extra space allocated during each reallocation is determined by the increment that you specify when you create the vector. If you don't specify an increment, the vector's size is doubled by each allocation cycle.

Vector defines these protected data members:

int capacityIncrement;
int elementCount;
Object elementData[ ];

The increment value is stored in capacityIncrement. The number of elements currently in the vector is stored in elementCount. The array that holds the vector is stored in elementData.

Because Vector implements List, you can use a vector just like you use an ArrayList instance. You can also manipulate one using its legacy methods. For example, after you instantiate a Vector, you can add an element to it by calling addElement(). To obtain the element at a specific location, call elementAt(). To obtain the first element in the vector, call firstElement(). To retrieve the last element, call lastElement(). You can obtain the index of an element by using indexOf() and lastIndexOf(). To remove an element, call removeElement() or removeElementAt().

The following program uses a vector to store various types of numeric objects. It demonstrates several of the legacy methods defined by Vector. It also demonstrates the Enumeration interface.

import java.util.*;

class VectorDemo {
    public static void main(String args[]) {
        // initial size is 3, increment is 2
        Vector<Object> v = new Vector<>(3, 2);
        System.out.println("Initial size: " + v.size());
        System.out.println("Initial capacity: " + v.capacity());
        
        v.addElement(Integer.valueOf(1));
        v.addElement(Integer.valueOf(2));
        v.addElement(Integer.valueOf(3));
        v.addElement(Integer.valueOf(4));
        
        System.out.println("Capacity after four additions: " + v.capacity());
        
        v.addElement(Double.valueOf(5.45));
        System.out.println("Current capacity: " + v.capacity());
        
        v.addElement(Double.valueOf(6.08));
        v.addElement(Integer.valueOf(7));
        System.out.println("Current capacity: " + v.capacity());
        
        v.addElement(Float.valueOf(9.4f));
        v.addElement(Integer.valueOf(10));
        System.out.println("Current capacity: " + v.capacity());
        
        v.addElement(Integer.valueOf(11));
        v.addElement(Integer.valueOf(12));
        
        System.out.println("First element: " + v.firstElement());
        System.out.println("Last element: " + v.lastElement());
        
        if(v.contains(Integer.valueOf(3)))
            System.out.println("Vector contains 3.");
        
        // enumerate the elements in the vector.
        Enumeration<Object> vEnum = v.elements();
        System.out.println("\nElements in vector:");
        while(vEnum.hasMoreElements())
            System.out.print(vEnum.nextElement() + " ");
        System.out.println();
    }
}

The output from this program is shown here:

Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12

With the release of Java 2, Vector adds support for iterators. Instead of relying on an enumeration to cycle through the objects (as the preceding program does), you now can use an iterator. For example, the following iterator-based code can be substituted into the program:

// use an iterator to display contents
Iterator vItr = v.iterator();
System.out.println("\\nElements in vector:");
while(vItr.hasNext())
System.out.print(vItr.next() + " ");
System.out.println();

Because enumerations are not recommended for new code, you will usually use an iterator to enumerate the contents of a vector. Of course, much legacy code exists that employs enumerations. Fortunately, enumerations and iterators work in nearly the same manner.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)