Vector Class in Java

Vector Class in Java

Last updated on 21st Sep 2020, Artciles, Blog

About author

Kumaran (Sr Technical Project Manager - Java )

He is a TOP-Rated Domain Expert with 11+ Years Of Experience, Also He is a Respective Technical Recruiter for Past 5 Years & Share's this Informative Articles For Freshers

(5.0) | 15437 Ratings 465

Vector implements List Interface. Like ArrayList it also maintains insertion order but it is rarely used in a non-thread environment as it is synchronized and due to which it gives poor performance in searching, adding, delete and update of its elements.

Creation of vector class object

There are three ways to create vector class object:

Method 1:

Syntax:

  • Vector vec = new Vector();

Subscribe For Free Demo

Error: Contact form not found.

It creates an empty Vector with the default initial capacity of 10. It means the Vector will be resized when the 11th element needs to be inserted into the Vector. Note: By default the vector doubles its size. i.e. In this case the Vector size would remain 10 till 10 insertions and once we try to insert the 11th element It would become 20 (double of default capacity 10).

Method 2:

Syntax:

  • Vector object= new Vector(int initialCapacity)

Example:

  • Vector vec = new Vector(3);

It will create a Vector of initial capacity of 3.

Method 3:

Syntax:

  • Vector object= new vector(int initialcapacity, capacityIncrement)

Example:

  • Vector vec= new Vector(4, 6)

Here we have provided two arguments. The initial capacity is 4 and capacityIncrement is 6. It means upon insertion of the 5th element the size would be 10 (4+6) and on 11th insertion it would be 16(10+6).

Complete Example of Vector in Java:

  • import java.util.*;

    public class VectorExample {

          public static void main(String args[]) {

          /* Vector of initial capacity(size) of 2 */

          Vector<String> vec = new Vector<String>(2);

     

          /* Adding elements to a vector*/

          vec.addElement(“Apple”);

          vec.addElement(“Orange”);

          vec.addElement(“Mango”);

          vec.addElement(“Fig”);

     

          /* check size and capacityIncrement*/

          System.out.println(“Size is: “+vec.size());

          System.out.println(“Default capacity increment is: “+vec.capacity());

     

          vec.addElement(“fruit1”);

          vec.addElement(“fruit2”);

          vec.addElement(“fruit3”);

     

          /*size and capacityIncrement after two insertions*/

          System.out.println(“Size after addition: “+vec.size());

          System.out.println(“Capacity after increment is: “+vec.capacity());

     

          /*Display Vector elements*/

          Enumeration en = vec.elements();

          System.out.println(“\nElements are:”);

          while(en.hasMoreElements())

             System.out.print(en.nextElement() + ” “);

       }

    }

Output:

Size is: 4

Default capacity increment is: 4

Size after addition: 7

Capacity after increment is: 8

Elements are:

Apple Orange Mango Fig fruit1 fruit2 fruit3

Course Curriculum

Enroll in Java Training Make You Expert in Java Platforms

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

Commonly used methods of Vector Class:

  • void addElement(Object element): It inserts the element at the end of the Vector.
  • int capacity(): This method returns the current capacity of the vector.
  • int size(): It returns the current size of the vector.
  • void setSize(int size): It changes the existing size with the specified size.
  • boolean contains(Object element): This method checks whether the specified element is present in the Vector. If the element is found it returns true or false.
  • boolean containsAll(Collection c): It returns true if all the elements of collection c are present in the Vector.
  • Object elementAt(int index): It returns the element present at the specified location in Vector.
  • Object firstElement(): It is used for getting the first element of the vector.
  • Object lastElement(): Returns the last element of the array.
  • Object get(int index): Returns the element at the specified index.
  • boolean isEmpty(): This method returns true if Vector doesn’t have any element.
  • boolean removeElement(Object element): Removes the specified element from vector.
  • boolean removeAll(Collection c): It Removes all those elements from vectors which are present in the Collection c.
  • void setElementAt(Object element, int index): It updates the element of the specified index with the given element.

How To Create A Vector In Java?

You can create a Vector object using any of the following Vector constructor methods.

Constructor PrototypeDescription
vector()This is the default constructor of the Vector class. It creates an empty vector with size 10.
vector(int initialCapacity)This overloaded constructor constructs an empty Vector object with the capacity = initialCapacity.
vector(int initialCapacity, int capacityIncrement)This constructor method creates an empty Vector object with specified initialCapacity and capacityIncrement.
Vector( Collection< ? extends E> c)A Vector object is created with the initial elements from specified collection c.

Let’s look at each of the constructors to initialize Vector objects.

Initialize Vector

(i) Vector()

This is the default constructor of the Vector class. When you invoke this constructor, a Vector object of default size 10 is created.

The general syntax of this method is:

  • Vector object = new Vector();

For Example,

  • Vector vec1 = new Vector ();

The above statement creates a new Vector ‘vec1’ with size 10.

(ii) Vector(int initialCapacity)

The overloaded constructor of the Vector class accepts ‘initialCapacity’ as the argument. This constructor creates a Vector object with the specified capacity.

The general syntax of the method is:

  • Vector object = new Vector (initialCapacity);

For Example,

  • Vector vec1 = new Vector (10);

The above programming statement will create a Vector object ‘vec1’ with the capacity of 10 i.e. this Vector can store up to 10 elements.

(iii) Vector(int initialCapacity, int capacityIncrement)

This is yet another overloaded constructor of Vector class and it creates a Vector object with the specified initial capacity and increment for the capacity.

The general syntax for this method is:

  • Vector object = new Vector (initialCapacity, capacityIncrement);

For Example,

  • Vector vec1 = new Vector(5,10);

In the above statement, the initial capacity of the Vector is 5 and increment is 10. This means when the 6th element is inserted into the vector, the capacity of the vector will be incremented to 15 (5 + 10). Similarly, when the 16th element is inserted, the vector capacity of the Vector will be extended to 25 (15 +10).

(iv) Vector(Collection<? extends E> c)

The last overloaded constructor of the Vector class takes in a predefined collection as an argument and creates a Vector with all the elements from this collection as its elements.

The general syntax is:

  • Vector object = new Vector (Collection<? extends E> c);

Java Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

For Example,

  • Vector vec1 = new Vector(aList); where aList = {1,2,3,4,5};

The above statement will create a Vector ‘vec1’ with initial elements as {1,2,3,4, 5}.

Keeping all these descriptions in mind will let us implement a Vector program to understand these constructors better.

Conclusion

In this Article, we started with the Vector data structure in Java. Vectors are almost similar to an array in which the Vector elements are accessed using familiar indices. Vectors are called dynamic array and unlike arrays, the Vector size grows and shrinks automatically.

Vectors also have the capacity and increment features that can be used to create and reserve additional storage for future additions. Vector is a legacy class in java.util package of Java and is synchronized as well as thread-safe.

Thus, we should prefer vectors when we need dynamic size and also while we are working in a multi-threaded environment.

Are you looking training with Right Jobs?

Contact Us

Popular Courses