Java Vector Class
Overview
In this tutorial, we will learn about the in-built Java Vector Class. The Vector class is defined in java.util package.
Java Vector class
The Vector class implements a dynamic array of
objects. The size of a Vector can grow or shrink as needed to accommodate adding and removing items. Vector is synchronized and is thread-safe.
The class extends AbstractList and implements the List interface.
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
…}
E specifies the type of element that will be stored using Vector.
List is an ordered collection. We can access elements by their integer index or position in the list. Like an array, the items can be accessed using an integer index.
We can import the class using the following statement:
import java.util.Vector;
Methods
Vector defines several legacy methods and methods defined by List. Some of the methods are as follows:
Method | Description |
addElement(E element) | The element is added to the Vector. |
E elementAt(int index) | The method returns the element at the location specified by the index. |
int capacity() | The method returns the capacity of the vector. |
boolean contains(Object element) | The method returns true if the element is contained by the vector, and returns false if is not. |
void ensureCapacity(int size) | The method sets the minimum capacity of the vector to the specified size. |
Example Program
package com.testingdocs.java.tutorials; /********************************************* * Java Vector class demo * Program to demonstrate vector operations. * Java Tutorials - www.TestingDocs.com *********************************************/ import java.util.*; class VectorDemo { public static void main(String args[]) { //initial size is 2, increment is 2 Vector vector=new Vector(2,2); System.out.println("Initial size: "+ vector.size()); System.out.println("Initial capacity: "+ vector.capacity()); vector.addElement(1); vector.addElement(2); vector.addElement(3); vector.addElement(4); System.out.println("Capacity after 4 adds: "+ vector.capacity()); vector.addElement(5); vector.addElement(6); System.out.println("Current capacity:"+ vector.capacity()); System.out.println("Vector First element: "+vector.firstElement()); System.out.println("Vector Last element: "+vector.lastElement()); if(vector.contains(5)) System.out.println("Vector contains the element 5"); //Iterate the elements in the vector. Iterator<Integer> vItr =vector.iterator(); System.out.println("Elements in the vector:"); while(vItr.hasNext()) System.out.print(vItr.next() +" "); System.out.println(); } }
Sample Output
Initial size: 0
Initial capacity: 2
Capacity after 4 adds: 4
Current capacity:6
Vector First element: 1
Vector Last element: 6
Vector contains the element 5
Elements in the vector:
1 2 3 4 5 6
—
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :