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 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: 60Explaination 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 ofInteger. If it is, it adds it to thesum. - In the
mainmethod, an instance ofGFGwith a type ofIntegeris created. - Three integers are added to this
GFGinstance using theadd()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.