×

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

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

Java.lang.Exception.NoRunnableMethods

In Programming language, the java lang unexpected no precompiled methods error generally refers to a Junit exception that happens whenever Junit is incapable of locate the precompiled test methods. When...

4 minutes read.

How to handle NullPointerException in Java

Introduction: Throwable class is the super or root class of the java exception hierarchy which contains two sub-classes. The classes’ are- ExceptionError Exception: If you are doing any wrong things in a...

3 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Accessors and Mutator in Java

Introduction Accessors and mutators are used in Java to get and set the value of private fields, respectively. Accessors and mutators are both referred to as getters and setters, respectively. The...

6 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

10 minutes read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

How to find characters with the maximum number of times in a string java

Problem statement In this problem, users want to find the maximum count of a character from the string and return the character along with its count. Your task is to create...

3 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.