How to Implement a Custom Vector with Additional Functionality in Java?
Last Updated :
23 Feb, 2024
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
import java.io.*;
import java.util.Vector;
class GFG<E> extends Vector<E> {
public int calculateSum() {
int sum = 0 ;
for (E element : this ) {
if (element instanceof Integer) {
sum += (Integer) element;
}
}
return sum;
}
}
public class Main {
public static void main(String[] args) {
GFG<Integer> customVector = new GFG<>();
customVector.add( 10 );
customVector.add( 20 );
customVector.add( 30 );
int sum = customVector.calculateSum();
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.
Share your thoughts in the comments
Please Login to comment...