Java/J2EE and SOA (195 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (48 Blogs)
  • Comprehensive Java Course (1 Blogs)
  • Java/J2EE and SOA (195 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

What is Vector in Java and how do we use it?

Last updated on Aug 02,2019 134 Views
67 / 75 Blog from Java Fundamentals

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assement report and video recording

Vectors in Java are one of the most commonly used data structures in the programming world. We all know that Arrays are data structures that hold the data in a linear fashion. Vectors also store the data in a linear fashion, but unlike Arrays, they do not have a fixed size. Instead, their size can be increased on demand.

Vector class is a child class of AbstractList class and implements on List interface. To use Vectors, we first have to import Vector class from java.util package:

import java.util.Vector 

In this article, we will be discussing the following concepts of vectors:

Let’s get started!

Advantages of Vector in Java

  • The property of having a dynamic size is very much useful as it avoids the memory wastage in case we do not know the size of the data structure at the time of declaration. 
  • When we want to change the size of our data structure in the middle of a program, vectors can prove to be very useful. 

The property of having a dynamic size is not unique to Vectors in Java. Another data structure, known as ArrayList also shows the property of having a dynamic size. However, Vectors are different from ArrayLists due to a couple of reasons:

  • First, Vectors are synchronized which gives it an advantage over ArrayList as compared to multithreaded programs as there are risks of data corruption. 
  • Secondly, Vectors have some legacy functions which can be implemented only on vectors and not on ArrayLists.

How to Access Elements in Vector

We can access the data members simply by using the index of the element, just like we access the elements in Arrays.

Example- If we want to access the third element in a vector v, we simply refer to it as v[3].

Vectors Constructors

Listed below are the multiple variations of vector constructors available to use:

  1. Vector(int initialCapacity, int Increment) – Constructs a vector with given initialCapacity and its Increment in size.
  2. Vector(int initialCapacity)Constructs an empty vector with given initialCapacity. In this case, Increment is zero.
  3. Vector() – Constructs a default vector of capacity 10.
  4. Vector(Collection c)Constructs a vector with a given collection, the order of the elements is same as returned by the collection’s iterator.

There are also three protected parameters in vectors

  1. Int capacityIncrement()- It automatically increases the capacity of the vector when the size becomes greater than capacity.
  2. Int elementCount() – tell number of elements in the vector
  3. Object[] elementData() –  array in which elements of vector are stored

Most Common Errors in Declaration of Vectors

  • Vector throws an IllegalArgumentException if the InitialSize of the vector defined is negative.
  • If the specified collection is null, It throws NullPointerException 

Note: 

  1. If the vector increment is not specified then it’s capacity will be doubled in every increment cycle.
  2. The capacity of a vector cannot be below the size, it may equal to it.

Let’s consider an example of initializing Vectors Constructors.

Example: Initializing Vector Constructors

/ Java code illustrating Vector Constructors
import java.util.*; 
public class Main{ 
	public static void main(String[] args) 
	{ 
			// create default vector 
			Vector v1 = new Vector(); 
      	// create a vector of given Size
      		Vector v2 = new Vector(20);
      	// create a vector of given Size and Increment
      		Vector v3 = new Vector(30,10);
      		v2.add(100);
      		v2.add(100);
      	    v2.add(100);
      	// create a vector with given collection
			Vector v4 = new Vector(v2);

      	System.out.println("Vector v1 of capacity " + v1.capacity());
      	System.out.println("Vector v2 of capacity " + v2.capacity());
      	System.out.println("Vector v3 of capacity " + v3.capacity());
	System.out.println("Vector v4 of capacity " + v4.capacity()); 
	}

Output

Constructors - Vectors in Java - Edureka

Memory allocation of vectors

So far, you must have understood that Vectors do not have a fixed size, instead, they have the ability to change their size dynamically. One might think that the vectors allocate indefinite long space to store objects. But this is not the case. Vectors can change their size based on two fields ‘capacity’ and ‘capacityIncrement’. Initially, a size equal to ‘capacity’ field is allocated when a vector is declared. We can insert the elements equal to the capacity. But as soon as the next element is inserted,  it increases the size of the array by size ‘capacityIncrement’. Hence, it is able to change its size dynamically.

For a default constructor, the capacity is doubled whenever the capacity is full and a new element is to be inserted.

Example – Suppose we have a vector of InitialCapacity 5 and capacityIncrement of 2.So the initial size of the vector is 5 elements We insert 5 elements into this vector one by one, namely 1,2,3,4,5. When we try to insert another element into the vector namely 6, the size of the vector will be incremented by 2. Hence the size of the vector is now 7. So the vector easily adjusts its size according to the no. of elements. 

Another interesting point is that unlike arrays, vectors do not contain real objects, but only references to the objects. Hence, it allows objects of different data types to be stored in the same vector.

Methods in Vector

Let’s have a look at few very frequently used vector methods.

  • Boolean add(Object o) – It appends an element at the end of the vector.
// Java code showing boolean add() method 
import java.util.*; 
public class Main{
    public static void main (String[] args) {

        Vector v = new Vector();  // It creates a default vector 
        v.add(1);                 // Adds 1 at the end of the list
	   v.add("Java");           // Adds "Java" at the end of the list
	   v.add("is");             // Adds "is" at the end of the list
	   v.add("Fun");            // Adds "Fun" at the end of the list

	   System.out.println("The vector is " + v); 
	} 
}

Output
Boolean Add - Vectors in Java - Edureka

  • Void add (int Index, E element) – It adds the given element at the specified index in the vector
// Java code showing void add() method 
import java.util.*; 
public class Main{
	public static void main (String[] args) {

		Vector v = new Vector();    // It creates a default vector 

		v.add(0,1);                   // Adds 1 at the index 0
		v.add(1,"Java");              // Adds "Java" at the index 1
		v.add(2,"is");                // Adds "is" at the index 2
		v.add(3,"Fun");               // Adds "Fun" at the index 3
     	            v.add(4,"!!!");               // Adds "Fun" at the index 4
		System.out.println("The vector is " + v); 
	}
}

Output
Add -Edureka

  • Boolean Remove(object o) – It removes remove the element at the given index in the vector
// Java code showing boolean remove() method 
import java.util.*; 
public class Main{
	public static void main (String[] args) {

		Vector v = new Vector();    // It creates a default vector

		v.add(1);                   // Adds 1 at the end of the list
		v.add("Java");              // Adds "Java" at the end of the list
		v.add("is");                // Adds "is" at the end of the list
		v.add("Fun");               // Adds "Fun" at the end of the list

		System.out.println("Vector before removal " + v );
				v.remove(1);
				System.out.println("Vector after removal " + v );
	} 
    
}

Output
Remove - Edureka

  • Boolean removeElement(Object obj) It deletes the element by its name obj (not by index number)
// Java code showing removeElement() method 
import java.util.*; 
public class Main{
	public static void main (String[] args) {

		Vector v = new Vector();    // It creates a default vector 

		v.add(1);                   // Adds 1 at the end of the list
		v.add("Java");              // Adds "Java" at the end of the list
		v.add("is");                // Adds "is" at the end of the list
		v.add("Fun");               // Adds "Fun" at the end of the list

		System.out.println("Vector before removal " + v );
				v.removeElement("Java");
				System.out.println("Vector after removal " + v );
	} 
    
}

Output
RemoveElement - edureka

  • Int size() – It returns the size of the vector.
// Java code showing size() method 
import java.util.*; 
public class Main{
	public static void main (String[] args) {

		Vector v = new Vector();    // It creates a default vector 

		v.add(0,1);                   // Adds 1 at the index 0
		v.add(1,"Java");              // Adds "Java" at the index 1
		v.add(2,"is");                // Adds "is" at the index 2
		v.add(3,"Fun");               // Adds "Fun" at the index 3

		System.out.println("The vector size is " + v.size()); 
	}   
}

Output
Size - Edureka

  • Int Capacity() – It returns the capacity of the vector
// Java code showing capacity() method 
import java.util.*; 
public class Main{
	public static void main (String[] args) {

		Vector v = new Vector();    // It creates a default vector 

		v.add(0,1);                   // Adds 1 at the index 0
		v.add(1,"Java");              // Adds "Java" at the index 1
		v.add(2,"is");                // Adds "is" at the index 2
		v.add(3,"Fun");               // Adds "Fun" at the index 3

		System.out.println("The vector capacity  is " + v.capacity()); 
	} 
    
}

Output

  • Object get(int index) –  It returns the element at the given position in the vector
// Java code showing get() method 
import java.util.*; 
public class Main{
	public static void main (String[] args) {

		Vector v = new Vector();    // It creates a default vector 

		v.add(1);                   // Adds 1 at the end of the list
		v.add("Java");              // Adds "Java" at the end of the list
		v.add("is");                // Adds "is" at the end of the list
		v.add("Fun");               // Adds "Fun" at the end of the list

		System.out.println("The element at index 1 is " + v.get(1)); 
	}
}

Output
Get - Edureka

  • Object firstElement() – It returns the first element
// Java code showing firstElement() method 
import java.util.*; 
public class Main{
	public static void main (String[] args) {

		Vector v = new Vector();    // It creates a default vector

		v.add(1);                   // Adds 1 at the end of the list
		v.add("Java");              // Adds "Java" at the end of the list
		v.add("is");                // Adds "is" at the end of the list
		v.add("Fun");               // Adds "Fun" at the end of the list

		System.out.println("The first element is  " + v.firstElement()); 
	} 
    
}

Output

  • Object lastElement() – It returns the last element
// Java code showing lastElement() method 
import java.util.*; 
public class Main{
	public static void main (String[] args) {

		Vector v = new Vector();    // It creates a default vector 

		v.add(1);                   // Adds 1 at the end of the list
		v.add("Java");              // Adds "Java" at the end of the list
		v.add("is");                // Adds "is" at the end of the list
		v.add("Fun");               // Adds "Fun" at the end of the list

		System.out.println("The last element is  " + v.lastElement()); 
	} 
}

Output
Last Element - Edureka

  •  Boolean equals(Object o) – It compares the vector with the specified object for equality. It returns true if all elements are true at their corresponding indices
// Java code showing boolean equals() method 
import java.util.*; 
public class Main{
	public static void main (String[] args) {

		Vector v = new Vector();    // It creates a default vector
		Vector vcopy = new Vector();

		v.add(1);                   // Adds 1 at the end of the list
		v.add("Java");              // Adds "Java" at the end of the list
		v.add("is");                // Adds "is" at the end of the list
		v.add("Fun");               //Adds "Fun" at the end of the list

		vcopy.add(0,1);             // Adds 1 at the index 0
		vcopy.add(1,"Java");        // Adds "Java" at the index 1
		vcopy.add(2,"is");          // Adds "is" at the index 2
		vcopy.add(3,"Fun");         // Adds "Fun" at the index 3
     	     vcopy.add(4,"!!!");         // Adds "Fun" at the index 4
				if(v.equals(vcopy))
		    System.out.println("Both vectors are equal" );
		else
        	System.out.println("Vectors are not equal" );

	} 
    
}

Output
Equals - Vectors in Java - Edureka

  • Void trimtosize() – This method removes extra capacity and keeps the capacity just to hold the elements i.e. equal to the size
// Java code showing trimToSize() method 
import java.util.*; 
public class Main{
	public static void main (String[] args) {

		Vector v = new Vector();    // It creates a default vector 

		v.add(0,1);                   // Adds 1 at the index 0
		v.add(1,"Java");              // Adds "Java" at the index 1
		v.add(2,"is");                // Adds "is" at the index 2
		v.add(3,"Fun");               // Adds "Fun" at the index 3

		System.out.println("The vector capacity is " + v.capacity());
		v.trimToSize();
		System.out.println("The vector capacity is " + v.capacity()); 
	} 
}

Output
Trim - Vectors in Java - Edureka

Others Important Methods

By now you must have got a good idea on how to work with vectors. If you wish to explore more of the vector methods then have a look at the below-given table.

Name of the MethodFunction of the Method

Boolean isEmpty()

checks whether elements exist or not

Boolean contains(Object o)

used to check the existence of a specific element, say o

int indexOf(Object o)

It returns the index of the element o

void removeRange(int s, int e)

removes elements from the vector starting from s and ending with (e-1)

void clear()

removes all the elements

void ensureCapacity(int c)

It increases the capacity by c

void setSize(int s)

It sets the size to s. If the s > size, the extra capacity is filled with null values. If s < size, the extra elements beyond the s are deleted

Object elementAt(int a)

returns the element existing at index number a

Object set(int a, Object o)

replaces the element present at the index a with the given element o

Object[] toArray()

returns an array containing the same elements as the vector

Object clone()

The vector object is copied

Boolean addAll(Collection c)

adds all the elements of Collection c to the vector

Boolean addAll(int a, Collection c)

inserts all the elements of Collection c to the vector at the specified index a

Boolean retainAll(Collection c)

retains all the elements in the vector that also exist in Collection c

List subList(int s, int e)

returns the elements, as a List object, starting from s and ending with (e-1) from the vector.

As every good thing comes to an end, so is our blog on Vectors in Java. We hope that we were able to cover all the aspects of java vectors in this blog and you were able to gather some knowledge regarding Vectors.

Make sure you practice as much as possible and revert your experience.  

Check out the Java Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. 

Got a question for us? Please mention it in the comments section of this ‘Vectors in Java’ article and we will get back to you as soon as possible.

Comments
0 Comments

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.