Skip to main content

Practical-32

Write a Java Program to implement the methods of Vector Class.


Introduction

The Vector class in Java is a type of collection that stores elements in a particular order. It is very similar to an ArrayList except for the fact that a Vector is thread-safe, which means multiple threads can operate on it without corruption. In addition, it is synchronized, so any operation on a Vector will be mutually exclusive and can be used in multi-threaded environments. The Vector class provides methods for manipulating its elements, such as adding, removing, finding, and sorting elements. This Java Tutorial explains how to implement Vector class in code.

Code

import java.util.Vector;

public class VectorClass {

public static void main(String[] args) {

// Create a Vector
Vector <String> vector = new Vector <String>();

// Add elements to Vector
vector.add("Item1");
vector.add("Item2");
vector.add("Item3");
vector.add("Item4");

// Remove an element from the Vector
vector.remove("Item3");

// Find an element in the Vector
boolean contains = vector.contains("Item2");
if (contains)
System.out.println("Vector contains Item2");
else
System.out.println("Vector does not contain Item2");

// Sort the elements in the Vector
vector.sort(null);
for (String element : vector) {
System.out.println(element);
}
}
}

Output

Vector contains Item2 Item1 Item2 Item4

Explanation

This program creates a Vector of strings and then adds four elements to it. It then removes an element from the Vector and performs a search to find an element. Finally, it sorts the Vector using the sort() method.

The Vector class provides a set of methods for manipulating its elements, such as adding, removing, finding, and sorting elements.