×

Vectors in Java

Vector Class

We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can modify its size, and we can utilise all the List interface's methods in vectors.

Vectors and the ArrayList are comparable. However, there are two differences:

  • The vector is coordinated.
  • There are several legacy methods in Java Vector that are not a part of a collections framework.

The syntax for Vector class

public class Vector<E>  extends Object<E>  implements List<E>, Cloneable, Serializable 

The syntax for the creation of vector

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

Example for vector creation

Vectorcreation.java

import java.io.*;
import java.util.*;
public class Vectorcreation
{
public static void main(String[] args) {
    // Integer type vector is created
        Vector<Integer> vector= new Vector<>();


        // String type vector is created
        Vector<String> vector1= new Vector<>();

}
}

Output

Vectors in Java

Constructors used in Vector class

  1. vector()
    A vector of default size ten is created
  2. vector(int initialCapacity)
    An empty vector is created, and the size will be zero with specified capacity and increment.
  3. vector(int initialCapacity, int capacityincrement)
    An empty vector is created with specified capacity and increment value.
  4. Vector( Collection<? extends E> c)
    Created a vector that contains elements of c

Methods in Vectors

1. Add elements to the vector

  • add()
    It adds an element to the end of the given vector
  • add(index, element)
    It adds described element at the preferred position
  • addAll(vector)
    It adds a vector to a vector

Program for the addition of  elements to vectors

Vectorsadd.java

import java.util.Vector;
import java.io.*;


class Vectorsadd {
    public static void main(String[] args) {
        // Integer vector with name numbers is defined
        Vector<Integer> numbers= new Vector<>();


        //Use the add() method to add numbers 10 and 20 to the vector 
        numbers.add(10);
        numbers.add(20);
        System.out.println("Vector after adding 10 and 20 is : " +numbers);
        // Using index number
        numbers.add(2,50);
        System.out.println("Vector: " +numbers);


        // Using addAll()
        // adding one vector number to the vector primes
        Vector<Integer> primes = new Vector<>();
        primes.add(3);


        primes.addAll(numbers);
        System.out.println("New Vector: " + primes);
    }
}

Output

Vectors in Java

2. Accessing elements in the vector

To access elements of the vector, we use predefined methods of vector class such as get(index) and iterator methods.

1.get(index)

   It returns an element specified by the given index

Program for accessing elements of the vector using the get(index) method

AccessEle.java

import java.util.Vector;
class AccessEle {
    public static void main(String[] args) {
        Vector<String> cars= new Vector<>();
        cars.add("BMW");
        cars.add("Range Rover");
        cars.add("Ford");


        // Using get()
        String element = cars.get(2);
        System.out.println("Element at index 2: " + element);
    }
}

Output

Vectors in Java

2.iterator()

  It is used to access elements of vector sequentially

Program for accessing elements of the vector using the iterator method

AccessEle.java

import java.util.Vector;
import java.util.Iterator;
class AccessEle {
    public static void main(String[] args) {
        Vector<String> cars= new Vector<>();
        cars.add("BMW");
        cars.add("Range Rover");
        cars.add("Ford");
         // Using iterator()
        Iterator<String> iterate = cars.iterator();
        System.out.print("Vector: ");
        while(iterate.hasNext()) {
            System.out.print(iterate.next());
            System.out.print(", ");
    }
    }
}

Output

Vectors in Java

3. Removing elements in the vector

To remove some aspects from the vector

1. remove(index)

We can delete a particular index element from the vector using this method.

Program for removing elements of the vector using the remove(index) method

Remove.java

import java.util.Vector;
import java.util.Iterator;
class Remove {
    public static void main(String[] args) {
        Vector<String> cars= new Vector<>();
        cars.add("BMW");
        cars.add("Range Rover");
        cars.add("Ford");
        // Using remove(index) to remove element at index 1
        String element = cars.remove(1);
        System.out.println("Removed Element: " + element);
        System.out.println("New Vector: " + cars);
    }}

Output

Vectors in Java

2. clear()

Using this method, we can clear all elements from a particular vector.

Program for removing elements of vector using clear(index) method

Clear.java

import java.util.Vector;
import java.util.Iterator;
class Clear{
    public static void main(String[] args) {
        Vector<String> cars= new Vector<>();
        cars.add("BMW");
        cars.add("Range Rover");
        cars.add("Ford");


         // Using clear()
        cars.clear();
        System.out.println("Vector after clear(): " + cars);
    }
}

Output

Vectors in Java

Example program for vectors in Java

Example1.java

import java.util.*;  
public class Example1 {  
       public static void main(String args[]) {  
        //Create an empty Vector        
        Vector<Integer> v = new Vector<>();  
        //Add elements in the vector  
        v.add(10);  
        v.add(20);  
        v.add(30);  
        v.add(40);  
        v.add(50);  
        //Display the vector elements  
        System.out.println("Values in vector: " +v);  
        //use the remove() method to delete the first occurrence of an element  
        System.out.println("Remove first occurrence of element 20: "+v.remove((Integer)20));  
        System.out.println("Values in vector: " +v);  
        //Remove an element  at index 5
        v.removeElementAt(5);        
        System.out.println("Vector element after removal: " +v);  
// Hash code is printed
        System.out.println("Hash code of this vector = "+v.hashCode());  
        // we will get element at the specified index  
        System.out.println("Element at index 1 is = "+v.get(1));  
          }  
}  

Output

Vectors in Java

Related Topics

How to Iterate List in Java?

List is a Collection foundation interface in Java. It enables us to keep the collection of objects in order. The four classes that make up the List interface implementation are...

3 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest. This keyword is used in Java. this keyword is...

5 minutes read.

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if...

6 minutes read.

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

File Operation in Java

In Java, a file is an Abstract data type. These are used to store the data which is related. Files are named storage locations. With a file we can perform...

7 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.