Java Vector clear() Method

Java Vector Java Vector

clear()The method isVectora common method provided by the class, used to remove all elements in the collection.

public void clear()

Method Function

clear()The main function of the method is to clearVectorall elements in it, making it an empty collection. After calling this method,Vectorofsize()will return 0, butcapacity()remains unchanged.

Key Features

  • RemoveVectorall elements in it
  • willVectorThe size is reset to 0
  • Does not changeVectorthe capacity
  • The time complexity of this operation is O(n), where n isVectorthe size

Method Implementation Principle

In Java'sVectorclass,clear()the implementation of the method is actually done by callingremoveAllElements()method:

Example

public void clear() {
    removeAllElements();
}

removeAllElements()The internal implementation of the method iterates overVectorall elements in it, and sets each position tonull, and resets the element counter to 0.

Source Code Analysis

Example

public synchronized void removeAllElements() {
    modCount++;
    // Set all elements to null
    for (int i = 0; i < elementCount; i++)
        elementData[i] = null;
    elementCount = 0;  // Reset element counter
}

Usage Example

Basic Usage

Example

import java.util.Vector;

public class VectorClearExample {
    public static void main(String[] args) {
        // Create a Vector and add elements
        Vector<String> fruits = new Vector<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
       
        System.out.println("Vector before clear: " + fruits);
        System.out.println("Size before clear: " + fruits.size());
       
        // Use the clear() method to clear the Vector
        fruits.clear();
       
        System.out.println("Vector after clear: " + fruits);
        System.out.println("Size after clear: " + fruits.size());
    }
}

Output result

清空前的 Vector: [Apple, Banana, Orange]
清空前的大小: 3
清空后的 Vector: []
清空后的大小: 0

Relationship with removeAllElements()

Example

Vector<Integer> numbers = new Vector<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);

// clear() and removeAllElements() have the same effect
numbers.clear();  // Clear the Vector
// Equivalent to
// numbers.removeAllElements();

Notes

Capacity Remains Unchanged

clear()The method only clearsVectorthe elements in it, but does not change its capacity. If you need to reduce the capacity at the same time, you can calltrimToSize()method:

Example

Vector<String> items = new Vector<>(20);  // Initial capacity is 20
items.add("A");
items.add("B");
items.add("C");

items.clear();  // Clear elements, capacity is still 20
items.trimToSize();  // Adjust the capacity to the current size (0)

Thread Safety

Vectoris thread-safe,clear()the method is also synchronized, and can be used safely in a multi-threaded environment.

Difference from ArrayList

AlthoughArrayListalso hasclear()method, butVectorofclear()is synchronized, whileArrayList's is not:

Example

// Vector's clear() is synchronized
public synchronized void clear() {
    removeAllElements();
}

// ArrayList's clear() is not synchronized
public void clear() {
    modCount++;
    for (int i = 0; i < size; i++)
        elementData[i] = null;
    size = 0;
}

FAQ

Q1: Does the clear() method release memory?

clear()The method sets all element references tonull, which allows these objects to be reclaimed by the garbage collector (if there are no other references to them). However,Vectorthe internal array itself will not be released, only the elements in it are cleared.

Q2: What is the difference between clear() and new Vector()?

  • clear()Reuses the existingVectorobject, only clears its elements
  • new Vector()Creates a brand newVectorobject, the oldVectorwill be garbage collected if there are no other references

Q3: How to determine whether a Vector is empty?

You can use theisEmpty()method:

Example

Vector<String> v = new Vector<>();
v.clear();
if (v.isEmpty()) {
    System.out.println("Vector is empty");
}

Summary

Vectorofclear()The method is a simple but practical tool for quickly clearing all elements in a collection. Understanding its working principle and characteristics helps write more efficient Java code. Remember its features related to capacity and thread safety, as well as best practices in specific scenarios.

Java Vector Java Vector

Other Extensions