Java Vector Class: A Beginner's Guide

Introduction

Hello there, future Java programmer! Today, we're going to dive into the exciting world of the Java Vector class. Don't worry if you've never written a line of code before – I'll be your friendly guide on this journey, just as I've been for countless students over my years of teaching.

Java - Vector Class

Imagine you're organizing a party, and you need a list to keep track of all your guests. That's essentially what a Vector does in Java – it's a dynamic list that can grow or shrink as needed. Pretty handy, right?

Class Declaration

Let's start with how we declare a Vector in Java. It's simpler than you might think!

import java.util.Vector;

Vector<String> guestList = new Vector<String>();

In this example, we're creating a Vector called guestList that will hold String objects (in this case, the names of our party guests). The <String> part tells Java what type of objects we'll be storing in our Vector.

Class Constructors

Now, let's look at the different ways we can create a Vector. It's like choosing how big of a party you want to throw!

// Default constructor
Vector<Integer> v1 = new Vector<>();

// Constructor with initial capacity
Vector<Integer> v2 = new Vector<>(10);

// Constructor with initial capacity and capacity increment
Vector<Integer> v3 = new Vector<>(10, 5);

// Constructor from another collection
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
Vector<Integer> v4 = new Vector<>(list);

Each of these constructors creates a Vector in a slightly different way:

  1. The default constructor creates an empty Vector.
  2. The second creates a Vector with an initial capacity of 10.
  3. The third creates a Vector with an initial capacity of 10, and it will increase by 5 each time it needs to grow.
  4. The last one creates a Vector from an existing collection (in this case, an ArrayList).

Class Methods

The Vector class comes with a toolbox full of useful methods. Let's take a look at some of the most common ones:

Method Description
add(E element) Adds an element to the end of the Vector
add(int index, E element) Inserts an element at the specified position
get(int index) Returns the element at the specified position
remove(int index) Removes the element at the specified position
size() Returns the number of elements in the Vector
clear() Removes all elements from the Vector
contains(Object o) Returns true if the Vector contains the specified element

Methods Inherited

Vector isn't a lone wolf – it inherits methods from its parent classes too. Some of these include:

  • From AbstractList: hashCode(), equals()
  • From AbstractCollection: toString()
  • From Object: clone(), finalize()

These inherited methods give Vector even more functionality out of the box!

Adding Elements and Iterating a Vector Example

Now, let's put our knowledge into practice with a fun example. We'll create a Vector of our favorite ice cream flavors and then print them out.

import java.util.Vector;

public class IceCreamParty {
    public static void main(String[] args) {
        // Create a new Vector to store ice cream flavors
        Vector<String> iceCreamFlavors = new Vector<>();

        // Add some flavors to our Vector
        iceCreamFlavors.add("Chocolate");
        iceCreamFlavors.add("Vanilla");
        iceCreamFlavors.add("Strawberry");
        iceCreamFlavors.add("Mint Chip");

        // Print out all the flavors
        System.out.println("Our ice cream flavors:");
        for (String flavor : iceCreamFlavors) {
            System.out.println("- " + flavor);
        }

        // Let's add another flavor at a specific position
        iceCreamFlavors.add(2, "Cookie Dough");

        // Print out the updated list
        System.out.println("\nUpdated ice cream flavors:");
        for (int i = 0; i < iceCreamFlavors.size(); i++) {
            System.out.println((i+1) + ". " + iceCreamFlavors.get(i));
        }
    }
}

Let's break this down:

  1. We start by creating a new Vector called iceCreamFlavors.
  2. We add four flavors using the add() method.
  3. We use a for-each loop to print out all the flavors.
  4. We then add "Cookie Dough" at index 2 (which will be the third position).
  5. Finally, we use a traditional for loop to print out the updated list with numbering.

Output

When you run this code, you'll see something like this:

Our ice cream flavors:
- Chocolate
- Vanilla
- Strawberry
- Mint Chip

Updated ice cream flavors:
1. Chocolate
2. Vanilla
3. Cookie Dough
4. Strawberry
5. Mint Chip

And there you have it! You've just created, modified, and iterated through a Vector. Doesn't that make you feel like a proper Java programmer already?

Remember, practice makes perfect. Try creating Vectors with different types of objects, or experiment with the other methods we discussed. Before you know it, you'll be manipulating Vectors like a pro!

Java's Vector class is a powerful tool in your programming toolkit. While it's been largely superseded by ArrayList in modern Java programming due to performance reasons, understanding Vector is still valuable, especially when working with legacy code or when you need a thread-safe dynamic array.

So, keep coding, keep learning, and most importantly, keep having fun with Java!

Credits: Image by storyset