Vector Class in Java with Examples

I am vigneshwaralingam. I am here to explain about the vector class in Java with examples in this article.In this article we will learn about how to create a vector class in java, why we used it in java, what is the advantages and disadvantages,and full details about the vector class in Java.

Java Vector class with examples

class with examples

Table of contents:

  • Introduction
  • Key features of vector class in Java
  • Where it is available
  • Why we used vector class in Java
  • Why this is better than arrays
  • Vector class creation
  • Important methods in vector class
  • Common errors while using vector class in Java
Introduction

This vector class in Java is defined as the following words.

Vector in  java is a dynamic arrays that allows resizing and can grow or shrink as needed.

Key features of vector class in Java

 Here’s the explanation of the key features of the vector class in Java

1. It Grows Automatically

2. It’s Thread-Safe

3. It Works Like a List

4. It Can Store Nulls

Where it is available

This package is available in java.util.vector. you can import by using this in your programs.

import java.util.vector
Why we used vector class in Java 
  • It can dynamicly resize
  • It is safe for concurrent operations
  • Suitable for the legacy code that requires synchronisation
  • It can hold diffrent types of objects using generics
Why this is better than arrays
  • Arrays are not synchronised vectors are synchronised
  • Arrays have a fixed size, vectors have not the fixed size
  • It provides a build in functions in java
Vector class creation in Java

This can be created by three types , these are the following

  • Without size
  • With size
  • Generics

With size:

It Initializes the vector with a capacity of 20.

java 
  vector<Integer>vector=new vector<>(20);

Without size:

It Creates a default vector with an initial capacity of 10.

java 
  vector<Integer>vector=new vector<>();capacity

Generics:

It Creates a vector for storing a string.

java 
  vector<string>vector=new vector<>();
Important methods in vector class
  • Add
  • Get
  • Remove

 

Add methods:

Java
  vector.add(5);
  vector.add(10);
  System.out.println(vector);

Output

[5,10]

Get method:

System.out.println(vector.get(0));

Output

5

Remove method:

Java
  vector.remove(1);
  System.out.println(vector);

Output

[5]

Common errors while using vector class in Java
  • Accessing the index outside the vector size.
  • Adding null elements or accessing null elements.
  • Modifying a vector while iterating without proper synchronisation.

Leave a Comment

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

Scroll to Top