Open In App

How to Implement a Custom Vector with Additional Functionality in Java?

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, the Vector class is a part of the Java Collections Framework providing the Dynamic Arrays that can be resized. However, there might be scenarios where you need a Custom Vector with additional functionality tailored to your specific requirements.

Prerequisite

To follow along, you should have a Basic understanding of Java programming particularly knowledge of classes, arrays, and Java Collections Framework.

Example

Java




// Java Program to  implement a custom
// Vector with additional functionality
import java.io.*;
import java.util.Vector;
  
// CustomVector class extending Vector
class GFG<E> extends Vector<E> {
    // Method to calculate sum of elements
    public int calculateSum() {
        int sum = 0;
        // Iterating over elements
        for (E element : this) {
            // Checking if element is an Integer
            if (element instanceof Integer) {
                // Adding element to sum
                sum += (Integer) element;
            }
        }
        // Return sum of elements
        return sum;
    }
}
  
// Driver Class
public class Main {
    // Main Function
    public static void main(String[] args) {
        // Creating an instance of the CustomVector
        GFG<Integer> customVector = new GFG<>();
  
        // Adding elements to custom vector
        customVector.add(10);
        customVector.add(20);
        customVector.add(30);
  
        // Calculating the sum using custom method
        int sum = customVector.calculateSum();
  
        // Displaying the result
        System.out.println("Sum of elements: " + sum);
    }
}


Output:

Sum of elements: 60

Explaination of the above Program:

  • Method calculateSum() calculates the sum of elements in the vector.
  • The calculateSum() method iterates through the elements of the vector and checks if each element is an instance of Integer. If it is, it adds it to the sum.
  • In the main method, an instance of GFG with a type of Integer is created.
  • Three integers are added to this GFG instance using the add() method.
  • The calculateSum() method is then called to calculate the sum of the integers in the vector.
  • Finally, the sum is printed to the console.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads