Java Vector

Introduction

Vector in Java is a dynamic array that implements the List interface. It is part of the Java Collections Framework and is found in the java.util package. Vector is similar to ArrayList, but it is synchronized, making it thread-safe. This synchronization ensures that Vector can be used in a multi-threaded environment without additional synchronization.

Table of Contents

  1. What is a Vector?
  2. Key Points About Vector
  3. Creating a Vector and Adding Elements
  4. Accessing Elements in a Vector
  5. Modifying Elements in a Vector
  6. Removing Elements from a Vector
  7. Iterating Over a Vector
  8. Searching for Elements in a Vector
  9. Vector of User-Defined Objects
  10. Common Vector Methods
  11. Conclusion

1. What is a Vector?

A Vector is a dynamic array that can grow or shrink in size as needed. It is synchronized, making it thread-safe for use in concurrent applications. Vector is part of the java.util package and implements the List interface, allowing it to be used like any other list in Java.

2. Key Points About Vector

  • Dynamic Array: Can grow and shrink in size.
  • Synchronized: Thread-safe for concurrent access.
  • Implements List: Supports all list operations.
  • Allows Duplicates and Nulls: Can contain duplicate elements and null values.

3. Creating a Vector and Adding Elements

To create a Vector, you can use the Vector constructor. You can then use methods such as add to add elements to the vector.

Example:

In this example, we create a Vector of strings and add a few elements to it.

import java.util.Vector;

public class VectorExample {
    public static void main(String[] args) {
        // Creating a Vector
        Vector<String> fruits = new Vector<>();

        // Adding elements to the Vector
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Displaying the Vector
        System.out.println("Vector: " + fruits);
    }
}

Output:

Vector: [Apple, Banana, Cherry]

4. Accessing Elements in a Vector

You can access elements in a Vector using methods such as get, firstElement, and lastElement.

Example:

In this example, we demonstrate how to access elements in a Vector.

import java.util.Vector;

public class AccessVector {
    public static void main(String[] args) {
        // Creating a Vector
        Vector<String> fruits = new Vector<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Accessing elements
        System.out.println("First element: " + fruits.firstElement());
        System.out.println("Last element: " + fruits.lastElement());
        System.out.println("Element at index 1: " + fruits.get(1));
    }
}

Output:

First element: Apple
Last element: Cherry
Element at index 1: Banana

5. Modifying Elements in a Vector

You can modify elements in a Vector using methods such as set.

Example:

In this example, we demonstrate how to modify elements in a Vector.

import java.util.Vector;

public class ModifyVector {
    public static void main(String[] args) {
        // Creating a Vector
        Vector<String> fruits = new Vector<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Modifying an element
        fruits.set(1, "Blueberry");

        // Displaying the updated Vector
        System.out.println("Updated Vector: " + fruits);
    }
}

Output:

Updated Vector: [Apple, Blueberry, Cherry]

6. Removing Elements from a Vector

You can remove elements from a Vector using methods such as remove.

Example:

In this example, we demonstrate how to remove elements from a Vector.

import java.util.Vector;

public class RemoveVector {
    public static void main(String[] args) {
        // Creating a Vector
        Vector<String> fruits = new Vector<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Removing elements
        fruits.remove(1); // Remove element at index 1
        fruits.remove("Cherry"); // Remove element by value

        // Displaying the Vector after removal
        System.out.println("Vector after removal: " + fruits);
    }
}

Output:

Vector after removal: [Apple]

7. Iterating Over a Vector

You can iterate over a Vector using various methods such as a simple for-each loop, iterator, and listIterator.

Example:

In this example, we demonstrate different ways to iterate over a Vector.

import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;

public class IterateVector {
    public static void main(String[] args) {
        // Creating a Vector
        Vector<String> fruits = new Vector<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Using simple for-each loop
        System.out.println("Using simple for-each loop:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }

        // Using iterator
        System.out.println("Using iterator:");
        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // Using listIterator
        System.out.println("Using listIterator:");
        ListIterator<String> listIterator = fruits.listIterator();
        while (listIterator.hasNext()) {
            System.out.println(listIterator.next());
        }
    }
}

Output:

Using simple for-each loop:
Apple
Banana
Cherry
Using iterator:
Apple
Banana
Cherry
Using listIterator:
Apple
Banana
Cherry

8. Searching for Elements in a Vector

You can search for elements in a Vector using methods such as contains, indexOf, and lastIndexOf.

Example:

In this example, we demonstrate how to check if a Vector contains a given element, find the index of the first occurrence of an element, and find the index of the last occurrence of an element.

import java.util.Vector;

public class SearchVector {
    public static void main(String[] args) {
        // Creating a Vector
        Vector<String> fruits = new Vector<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Banana");

        // Check if the Vector contains a given element
        System.out.println("Does the Vector contain 'Banana'? " + fruits.contains("Banana"));

        // Find the index of the first occurrence of an element
        System.out.println("Index of the first occurrence of 'Banana': " + fruits.indexOf("Banana"));

        // Find the index of the last occurrence of an element
        System.out.println("Index of the last occurrence of 'Banana': " + fruits.lastIndexOf("Banana"));
    }
}

Output:

Does the Vector contain 'Banana'? true
Index of the first occurrence of 'Banana': 1
Index of the last occurrence of 'Banana': 3

9. Vector of User-Defined Objects

You can use Vector to store user-defined objects. This involves creating a class for the objects you want to store and then creating a Vector to manage these objects.

Example:

In this example, we create a Person class and then create a Vector to store Person objects.

import java.util.Vector;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

public class UserDefinedObjectVector {
    public static void main(String[] args) {
        // Creating a Vector of Person objects
        Vector<Person> people = new Vector<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));

        // Displaying the Vector
        System.out.println("Vector of Person objects: " + people);
    }
}

Output:

Vector of Person objects: [Person{name='Alice', age=30}, Person{name='Bob', age=25}, Person{name='Charlie', age=35}]

10. Common Vector() Methods

Adding Elements

  • add(E e): Appends the specified element to the end of the vector.
  • add(int index, E element): Inserts the specified element at the specified position in the vector.

Removing Elements

  • remove(int index): Removes the element at the specified position in the vector.
  • remove(Object o): Removes the first occurrence of the specified element from the vector.
  • clear(): Removes all elements from the vector.

Accessing Elements

  • get(int index): Returns the element at the specified position in the vector.
  • firstElement(): Returns the first element in the vector.
  • lastElement(): Returns the last element in the vector.

Other Useful Methods

  • size(): Returns the number of elements in the vector.
  • isEmpty(): Returns true if the vector contains no elements.
  • contains(Object o): Returns true if the vector contains the specified element.
  • indexOf(Object o): Returns the index of the first occurrence of the specified element in the vector.
  • lastIndexOf(Object o): Returns the index of the last occurrence of the specified element in the vector.
  • toArray(): Returns an array containing all of the elements in the vector in proper sequence.

11. Conclusion

The Vector class in Java is a versatile, thread-safe data structure that provides dynamic array capabilities. It supports synchronized access to elements, making it suitable for concurrent applications. Understanding how to create, manipulate, and iterate over Vector can help you effectively manage collections of objects in your Java applications. With methods for adding, removing, accessing, iterating, and searching elements, the Vector class offers a comprehensive solution for dynamic array management in Java. However, due to its synchronization overhead, Vector may be slower than ArrayList in single-threaded contexts, so choose the appropriate data structure based on your specific needs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top