Java Vector size() Method
Vectorclass'ssize()method is used to obtain the currentVectornumber of elements contained in
Syntax Description
public int size()
Method Features
- Return type:
int - Return value: current
Vectornumber of elements in - Time complexity: O(1) (constant time)
Usage Examples
Basic Usage
Example
public class VectorSizeExample {
public static void main(String[] args) {
// Create a Vector
Vector<String> fruits = new Vector<>();
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Use the size() method to get the number of elements
int size = fruits.size();
System.out.println("Number of elements in Vector: " + size);
}
}
Output:
Vector 中的元素数量: 3
Difference from capacity
Beginners often confusesize()andcapacity()methods:
Example
numbers.add(1);
numbers.add(2);
System.out.println("Size: " + numbers.size()); // Output: 2
System.out.println("Capacity: " + numbers.capacity()); // Output: 10
size(): the number of elements currently storedcapacity(): the maximum number of elements the Vector can currently store (without needing to expand)
Common Application Scenarios
1. Iterating over a Vector
Example
System.out.println(vector.get(i));
}
2. Checking whether a Vector is empty
Although you can useisEmpty()method, you can also do this:
Example
System.out.println("Vector is empty");
}
3. Controlling the number of loop iterations
Example
vector.add("Item " + (vector.size() + 1));
}
Notes
Thread safety: Although
Vectoris thread-safe, butsize()the value returned by the method may become invalid immediately in a multi-threaded environment (if other threads are modifyingVector)。Performance considerations: for scenarios that require frequent insert and delete operations,
ArrayListusually compared toVectorhas better performance, becauseVectorthe synchronization operation brings additional overhead.Alternative solutions: in Java 5 and later versions, you can consider using
Collections.synchronizedList()to wrapArrayListto obtain a thread-safe list:
List<String> syncList = Collections.synchronizedList(new ArrayList<String>());
Summary
Vectorofsize()The method is a simple but very important method; it can help us:
- Understand how many elements the collection currently contains
- Control loops and iterations
- Check the state of the collection
AlthoughVectorits frequency of use in modern Java development has declined (replaced byArrayListreplaced), but in scenarios where thread-safe collections are needed, it is still a reliable choice. Understandingsize()The method is crucial for mastering the basic operations of the Java Collections Framework.
Java Vector