杰瑞科技汇

java vector util

Of course! When people refer to "Java Vector util," they are almost always talking about the java.util.Vector class. It's a fundamental part of Java's Collections Framework, though its role has evolved over time.

java vector util-图1
(图片来源网络,侵删)

Here’s a comprehensive breakdown of java.util.Vector, covering its core concepts, usage, and modern alternatives.


What is java.util.Vector?

Vector is a legacy class in Java that implements the List interface. It's essentially a dynamic array, meaning it can grow or shrink in size as you add or remove elements.

Key Characteristics:

  • Dynamic Sizing: You don't need to specify its size upfront. It automatically expands its internal storage when full.
  • Ordered: It maintains the insertion order of elements.
  • Allows Duplicates: It can store multiple null values and duplicate objects.
  • Legacy Thread-Safety: This is the most important and defining feature of Vector. All of its methods are synchronized. This means that only one thread can execute a method on a Vector instance at a given time, making it thread-safe.

Common Constructors

You typically create a Vector in one of three ways:

java vector util-图2
(图片来源网络,侵删)
import java.util.Vector;
// 1. Default constructor: Creates an empty Vector with an initial capacity of 10.
Vector<String> vector1 = new Vector<>();
// 2. Constructor with an initial capacity.
Vector<Integer> vector2 = new Vector<>(20); // Starts with space for 20 elements.
// 3. Constructor with an initial capacity and a capacity increment.
// The vector will grow by 10 elements each time it's full.
Vector<Double> vector3 = new Vector<>(5, 10);

Core Methods and Usage

Here are the most frequently used methods with examples.

Adding Elements

  • add(E e): Appends the specified element to the end of the vector.
  • add(int index, E e): Inserts the element at the specified position.
  • addAll(Collection<? extends E> c): Appends all elements of the given collection.
Vector<String> names = new Vector<>();
names.add("Alice");
names.add("Bob");
names.add(1, "Charlie"); // Insert at index 1
System.out.println(names); // Output: [Alice, Charlie, Bob]

Accessing Elements

  • get(int index): Returns the element at the specified position.
  • elementAt(int index): A legacy version of get().
  • firstElement(): Returns the first element.
  • lastElement(): Returns the last element.
  • size(): Returns the number of elements.
  • capacity(): Returns the current capacity (the size of the internal array).
System.out.println("Name at index 1: " + names.get(1)); // Output: Charlie
System.out.println("First Name: " + names.firstElement()); // Output: Alice
System.out.println("Total Names: " + names.size()); // Output: 3
System.out.println("Current Capacity: " + names.capacity()); // Output: 10 (from default constructor)

Removing Elements

  • remove(int index): Removes the element at the specified position.
  • remove(Object o): Removes the first occurrence of the specified element.
  • clear(): Removes all elements from the vector.
names.remove("Bob");
System.out.println("After removing Bob: " + names); // Output: [Alice, Charlie]
names.remove(0);
System.out.println("After removing index 0: " + names); // Output: [Charlie]

Iterating Over a Vector

You can use a standard enhanced for-loop, which is the most common and readable way.

Vector<String> fruits = new Vector<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
System.out.println("Fruit List:");
for (String fruit : fruits) {
    System.out.println("- " + fruit);
}

Searching

  • contains(Object o): Returns true if the vector contains the specified element.
  • indexOf(Object o): Returns the index of the first occurrence of the element, or -1 if not found.
System.out.println("Contains Banana? " + fruits.contains("Banana")); // Output: true
System.out.println("Index of Orange: " + fruits.indexOf("Orange")); // Output: 2

Thread-Safety: The synchronized Keyword

This is what sets Vector apart from its modern counterpart, ArrayList.

// Imagine multiple threads are trying to modify this vector
Vector<Integer> sharedVector = new Vector<>();
// Thread 1
new Thread(() -> {
    for (int i = 0; i < 1000; i++) {
        sharedVector.add(i);
    }
}).start();
// Thread 2
new Thread(() -> {
    for (int i = 1000; i < 2000; i++) {
        sharedVector.add(i);
    }
}).start();
// Because add() is synchronized, the threads will not corrupt the vector's internal state.
// The final size will be 2000.
try {
    Thread.sleep(1000); // Wait for threads to finish
} catch (InterruptedException e) {
    e.printStackTrace();
}
System.out.println("Final size of shared Vector: " + sharedVector.size()); // Output: 2000

The Catch: This thread-safety comes at a cost. Synchronization can introduce performance overhead. If multiple threads are frequently accessing the same Vector, the locking mechanism can become a bottleneck.

java vector util-图3
(图片来源网络,侵删)

Modern Alternatives: ArrayList vs. Vector

For most new Java code, you should prefer ArrayList over Vector. Here's a direct comparison:

Feature java.util.Vector java.util.ArrayList
Thread-Safety Yes, all methods are synchronized. No, not thread-safe by default.
Performance Slower in multi-threaded environments due to synchronization overhead. Faster in single-threaded environments than a synchronized Vector. Faster in single-threaded environments.
Legacy Yes, it's a legacy class from Java 1.0. No, it's the standard, modern implementation of the List interface.
Growth Policy Can specify a capacityIncrement. Doubles in size by default. Always doubles in size when it needs to grow.
Usage Rarely used in new applications. Consider CopyOnWriteArrayList for specific thread-safe scenarios. The default choice for any non-concurrent list.

When to use Vector today?

Very rarely. If you have a simple, read-only list that needs to be shared across threads and performance is not critical, Vector might be acceptable. However, there are almost always better options.


Better Thread-Safe Alternatives

If you need a thread-safe list, consider these modern alternatives from java.util.concurrent:

Collections.synchronizedList()

This is the most common way to get a thread-safe list. It wraps an ArrayList and synchronizes access to each individual method.

List<String> list = Collections.synchronizedList(new ArrayList<>());
// You must manually synchronize on the list when iterating!
synchronized (list) {
    for (String item : list) {
        // ... do something with item
    }
}

Why? It gives you thread safety without the performance penalty of synchronizing every single method call on Vector. You only pay for synchronization when you need it (e.g., during iteration).

CopyOnWriteArrayList

This is a specialized list designed for scenarios where reads vastly outnumber writes. When a write (add/remove) operation occurs, it creates a fresh copy of the underlying array.

  • Pros: Excellent for read-heavy, write-rarely scenarios. Iterators are "weakly consistent" and will not throw ConcurrentModificationException.
  • Cons: Can be very expensive for frequent write operations due to the copying overhead.
List<String> concurrentList = new CopyOnWriteArrayList<>();
concurrentList.add("One");
concurrentList.add("Two");
// Iteration is safe even if another thread modifies the list
for (String item : concurrentList) {
    System.out.println(item);
}

Summary and Best Practices

If you need... Use... Why?
A general-purpose list in a single-threaded application. ArrayList It's the standard, most efficient choice.
A list that will be accessed by multiple threads. Collections.synchronizedList(new ArrayList<>()) Provides thread safety with better performance than Vector.
A read-heavy list accessed by multiple threads. CopyOnWriteArrayList Optimized for scenarios where reads are far more common than writes.
Legacy code or a very specific, simple use case. Vector It's the only option if you absolutely must have a legacy Vector reference.

Final Recommendation: Avoid java.util.Vector in new code. It's a historical artifact. Start with ArrayList and if you need thread-safety, use Collections.synchronizedList() or a java.util.concurrent class.

分享:
扫描分享到社交APP
上一篇
下一篇