Vectors in Java

 

๐Ÿงญ Vectors in Java 

In Java, when we need to store a dynamic list of elements (that can grow or shrink during runtime), we use the Vector class.

Before modern collections like ArrayList were introduced, Vector was widely used to store dynamic data. Even today, it remains important for understanding the evolution of Java’s Collection Framework.


๐Ÿ”น What is a Vector?

A Vector in Java is a resizable array that can store elements of the same type.
Unlike regular arrays that have a fixed size, vectors automatically increase their capacity when more elements are added.

Vectors belong to the package:

java.util

๐Ÿ”น Key Features of Vectors

✅ Can grow or shrink dynamically
✅ Can store duplicate elements
✅ Maintains insertion order
Synchronized — thread-safe (unlike ArrayList)
✅ Provides many useful built-in methods for easy manipulation


๐Ÿ”น Syntax to Create a Vector

Vector<Type> vectorName = new Vector<Type>();

Example:

import java.util.Vector; public class Example { public static void main(String[] args) { Vector<Integer> numbers = new Vector<Integer>(); } }

๐Ÿ”น Adding Elements to a Vector

You can use the add() method to insert elements.

import java.util.Vector; public class AddExample { public static void main(String[] args) { Vector<String> fruits = new Vector<String>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); System.out.println("Fruits: " + fruits); } }

Output:

Fruits: [Apple, Banana, Cherry]

๐Ÿ”น Accessing Elements in a Vector

You can access elements using the get(index) method or an iterator.

System.out.println(fruits.get(1)); // prints Banana

Or using a loop:

for (int i = 0; i < fruits.size(); i++) { System.out.println(fruits.get(i)); }

๐Ÿ”น Updating and Removing Elements

Update an element:

fruits.set(1, "Blueberry"); System.out.println(fruits);

Output:

[Apple, Blueberry, Cherry]

Remove an element:

fruits.remove(2); System.out.println(fruits);

Output:

[Apple, Blueberry]

๐Ÿ”น Example 1: Basic Vector Operations

import java.util.Vector; public class VectorExample { public static void main(String[] args) { Vector<Integer> numbers = new Vector<Integer>(); // adding elements numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40); System.out.println("Initial Vector: " + numbers); // accessing elements System.out.println("First element: " + numbers.get(0)); // updating element numbers.set(2, 99); System.out.println("After update: " + numbers); // removing element numbers.remove(1); System.out.println("After removal: " + numbers); } }

Output:

Initial Vector: [10, 20, 30, 40] First element: 10 After update: [10, 20, 99, 40] After removal: [10, 99, 40]

๐Ÿ”น Iterating Through a Vector

You can traverse a Vector using:

1️⃣ For Loop

for (int i = 0; i < numbers.size(); i++) { System.out.println(numbers.get(i)); }

2️⃣ Enhanced For Loop (For-Each)

for (int num : numbers) { System.out.println(num); }

3️⃣ Iterator

import java.util.Iterator; Iterator<Integer> it = numbers.iterator(); while (it.hasNext()) { System.out.println(it.next()); }

๐Ÿ”น Vector Methods at a Glance

MethodDescriptionExample
add(element)    Adds element at the end    v.add(10)
add(index, element)    Inserts element at specific position    v.add(1, 25)
get(index)    Returns element at index    v.get(2)
set(index, element)    Replaces element    v.set(0, 99)
remove(index)    Removes element at index    v.remove(1)
clear()    Removes all elements    v.clear()
size()    Returns number of elements    v.size()
contains(value)    Checks if element exists    v.contains(30)
isEmpty()    Checks if vector is empty    v.isEmpty()
firstElement()    Returns first element    v.firstElement()
lastElement()    Returns last element    v.lastElement()
capacity()    Returns current capacity    v.capacity()

๐Ÿ”น Example 2: Using Vector Methods

import java.util.Vector; public class VectorMethods { public static void main(String[] args) { Vector<String> animals = new Vector<String>(); animals.add("Dog"); animals.add("Cat"); animals.add("Elephant"); animals.add("Tiger"); System.out.println("Animals: " + animals); System.out.println("First: " + animals.firstElement()); System.out.println("Last: " + animals.lastElement()); System.out.println("Contains Cat? " + animals.contains("Cat")); System.out.println("Size: " + animals.size()); System.out.println("Capacity: " + animals.capacity()); } }

Output:

Animals: [Dog, Cat, Elephant, Tiger] First: Dog Last: Tiger Contains Cat? true Size: 4 Capacity: 10

(By default, a Vector starts with a capacity of 10 and doubles when full.)


๐Ÿ”น Vector vs ArrayList

FeatureVectorArrayList
Synchronization            ✅ Synchronized (Thread-safe)        ❌ Not synchronized
Performance⚙️ Slower (because of synchronization)    ⚡ Faster
GrowthDoubles its size    Increases by 50%
Introduced inJDK 1.0 (Legacy class)    JDK 1.2
Use CaseMulti-threaded programs    Single-threaded programs

๐Ÿ”น Example 3: Copy All Elements from One Vector to Another

import java.util.Vector; public class CopyVector { public static void main(String[] args) { Vector<Integer> v1 = new Vector<Integer>(); v1.add(1); v1.add(2); v1.add(3); Vector<Integer> v2 = new Vector<Integer>(); v2.addAll(v1); System.out.println("Vector 1: " + v1); System.out.println("Vector 2: " + v2); } }

Output:

Vector 1: [1, 2, 3] Vector 2: [1, 2, 3]

๐Ÿ”น Example 4: Removing All Elements from a Vector

import java.util.Vector; public class ClearVector { public static void main(String[] args) { Vector<String> colors = new Vector<String>(); colors.add("Red"); colors.add("Blue"); colors.add("Green"); System.out.println("Before clear: " + colors); colors.clear(); System.out.println("After clear: " + colors); } }

Output:

Before clear: [Red, Blue, Green] After clear: []

๐Ÿ’ก Summary

ConceptDescription
Vector            Dynamic array from java.util package
Resizable            Grows automatically as elements are added
Thread-safe            Synchronized, safe for multi-threading
Common methods       add(), get(), set(), remove(), size(), capacity()
Alternative           ArrayList — faster but not synchronized

๐Ÿงพ Key Takeaway

Vectors are an important part of Java’s legacy collection classes.
Even though ArrayList is more commonly used today, understanding Vector helps build a solid foundation for Java Collection Framework concepts like synchronization and dynamic storage.

Example Programs

 1️⃣ Program to Store and Print 5 Student Names using a Vector

import java.util.Vector; public class StudentNames { public static void main(String[] args) { // Create a Vector to store student names Vector<String> students = new Vector<String>(); // Add 5 student names students.add("Asha"); students.add("Rahul"); students.add("Neha"); students.add("Vishal"); students.add("Anu"); // Display all student names System.out.println("List of Students:"); for (String name : students) { System.out.println(name); } } }

Output:

List of Students: Asha Rahul Neha Vishal Anu

 2️⃣ Program to Remove Duplicate Elements from a Vector

import java.util.Vector; public class RemoveDuplicates { public static void main(String[] args) { Vector<Integer> numbers = new Vector<Integer>(); // Adding elements (with duplicates) numbers.add(10); numbers.add(20); numbers.add(10); numbers.add(30); numbers.add(20); System.out.println("Original Vector: " + numbers); // Remove duplicates manually Vector<Integer> unique = new Vector<Integer>(); for (Integer n : numbers) { if (!unique.contains(n)) { unique.add(n); } } System.out.println("After removing duplicates: " + unique); } }

Output:

Original Vector: [10, 20, 10, 30, 20] After removing duplicates: [10, 20, 30]

3️⃣ Create a Vector of Integers and Find the Largest Element

import java.util.Vector; public class LargestElement { public static void main(String[] args) { Vector<Integer> numbers = new Vector<Integer>(); numbers.add(25); numbers.add(10); numbers.add(67); numbers.add(42); numbers.add(39); System.out.println("Vector elements: " + numbers); // Assume first element is largest initially int largest = numbers.get(0); for (int i = 1; i < numbers.size(); i++) { if (numbers.get(i) > largest) { largest = numbers.get(i); } } System.out.println("Largest element: " + largest); } }

Output:

Vector elements: [25, 10, 67, 42, 39] Largest element: 67

 4️⃣ Program to Copy All Elements from One Vector to Another

import java.util.Vector; public class CopyVector { public static void main(String[] args) { Vector<String> colors1 = new Vector<String>(); colors1.add("Red"); colors1.add("Green"); colors1.add("Blue"); // Create a new Vector and copy all elements Vector<String> colors2 = new Vector<String>(); colors2.addAll(colors1); System.out.println("Original Vector: " + colors1); System.out.println("Copied Vector: " + colors2); } }

Output:

Original Vector: [Red, Green, Blue] Copied Vector: [Red, Green, Blue]

5️⃣ Implement a Vector of Strings and Search for a Given Word

import java.util.Scanner; import java.util.Vector; public class SearchWord { public static void main(String[] args) { Vector<String> words = new Vector<String>(); Scanner sc = new Scanner(System.in); // Add words to the vector words.add("apple"); words.add("banana"); words.add("cherry"); words.add("grape"); words.add("mango"); System.out.println("Words in Vector: " + words); // Input word to search System.out.print("Enter a word to search: "); String searchWord = sc.nextLine(); // Check if word exists if (words.contains(searchWord)) { System.out.println(searchWord + " is found in the Vector!"); } else { System.out.println(searchWord + " is NOT found in the Vector!"); } sc.close(); } }

Example Output:

Words in Vector: [apple, banana, cherry, grape, mango] Enter a word to search: grape grape is found in the Vector!


Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism