BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Vector in Java

Last Updated: July 1, 2024 by Chaitanya Singh | Filed Under: java

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

Importing the Vector Class

import java.util.Vector;

Creating a Vector

Method 1:

Vector<String> vector = new Vector<>();

It creates an empty Vector with the default initial capacity of 10. It means the Vector will be re-sized when the 11th elements needs to be inserted into the Vector.

Note: By default 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:

Vector<String> vector = new Vector<>(10);

It will create a Vector of initial capacity of 10.

Method 3:

Vector<String> object= new vector<>(int initialcapacity, capacityIncrement)

Example:

Vector<String> vector = new Vector<>(4, 6)

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

Adding Elements

You can add elements to a Vector using the add method:

vector.add("Chaitanya");
vector.add("BeginnersBook");

Accessing Elements

You can access element using get() method. You can use enhanced for loop for iterating a vector.

String firstElement = vector.get(0);

for (String element : vector) {
System.out.println(element);
}

Modifying Elements

The set() method of vector class can be used to modify an element. In the following example, we are updating the first element (index 0) of the Vector.

vector.set(0, "New Element");

Removing Elements

You can use remove() method to remove an element at specific index or can specify the element which needs to be removed.

vector.remove(1); // Removes the second element
vector.remove("Chaitanya"); // Removes first occurrence of "Chaitanya"

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

Commonly used methods of Vector Class:

  1. void addElement(Object element): It inserts the element at the end of the Vector.
  2. int capacity(): This method returns the current capacity of the vector.
  3. int size(): It returns the current size of the vector.
  4. void setSize(int size): It changes the existing size with the specified size.
  5. boolean contains(Object element): This method checks whether the specified element is present in the Vector. If the element is been found it returns true else false.
  6. boolean containsAll(Collection c): It returns true if all the elements of collection c are present in the Vector.
  7. Object elementAt(int index): It returns the element present at the specified location in Vector.
  8. Object firstElement(): It is used for getting the first element of the vector.
  9. Object lastElement(): Returns the last element of the array.
  10. Object get(int index): Returns the element at the specified index.
  11. boolean isEmpty(): This method returns true if Vector doesn’t have any element.
  12. boolean removeElement(Object element): Removes the specifed element from vector.
  13. boolean removeAll(Collection c): It Removes all those elements from vector which are present in the Collection c.
  14. void setElementAt(Object element, int index): It updates the element of specifed index with the given element.

Vector Tutorials

Here is the list of Vector tutorials published on beginnersbook.com. Happy Learning :)

Vector basics

  • Get sub list from Vector
  • Sort Vector using Collections.sort()
  • Search element in Vector using index
  • Copy Elements of one Vector to another

Remove/Sort/Replace

  • Remove element from Vector
  • Remove element from specified index in Vector
  • Remove all elements from Vector
  • Replace element in Vector
  • Set Vector size

Iterator/ListIterator/Enumeration

  • Vector enumeration example
  • Vector Iterator example
  • Vector ListIterator example

Conversions

  • Convert Vector to List
  • Convert Vector to ArrayList
  • Convert Vector to String Array

Differences

  • Vector vs ArrayList

Reference

  • Documentation

Top Related Articles:

  1. StringJoiner toString() Method in Java
  2. Java StringBuffer toString()
  3. Java StringBuilder append() Method
  4. Examples of throws Keyword in Java
  5. Replace Vector elements using index – Java example

Tags: Collections, Java-Vector

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. J Padilha says

    April 7, 2016 at 11:15 AM

    Easy and straigthforward

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap