01
What is a Vector?
Vector is a resizable array
- Dynamic array. Grows automatically as elements are added — no fixed size like a plain array.
- Ordered & index-based, elements keep insertion order and are reachable by position.
02
Creating a Vector
Vector offers four constructors — the extra two exist so you can tune exactly how it grows.
Vector<String> v1 = new Vector<>(); // default capacity: 10
Vector<String> v2 = new Vector<>(50); // initial capacity: 50
Vector<String> v3 = new Vector<>(50, 20); // capacity 50, grows by exactly 20 each time it's full
Vector<String> v4 = new Vector<>(existingList); // pre-filled from another Collection
Choosing an initial capacity close to the expected final size avoids repeated internal resizing — useful when you already know roughly how many elements are coming.
03
Growth & Capacity
A Vector always has more room than it's using. size() is how many elements are actually stored; capacity() is how many it can hold before it needs to resize.
Default growth: doubles
Vector<Integer> v = new Vector<>(); // capacity 10
// add 11 elements...
v.capacity(); // 20 — capacity doubled once full
Fixed growth: capacityIncrement
Vector<Integer> v = new Vector<>(10, 5);
// once full, capacity grows by exactly 5 each time
// instead of doubling: 10 → 15 → 20 → 25 ...
Why this matters
Every resize copies every existing element into a new, bigger array — an O(n) operation. Sizing the initial capacity sensibly is the cheapest performance win available for a Vector that's going to hold a lot of data.
05
Common Methods
Vector supports the standard List operations, plus a set of older, Vector-specific method names left over from before the Collections Framework existed.
| Method | What it does |
|---|---|
add(x) / addElement(x) | Appends an element to the end |
get(i) / elementAt(i) | Returns the element at index i |
set(i, x) | Replaces the element at index i |
remove(i) / removeElement(x) | Removes by index, or by matching value |
firstElement() / lastElement() | Convenience access to the first / last element |
insertElementAt(x, i) | Inserts x at index i, shifting later elements right |
contains(x) / indexOf(x) | Membership check / position lookup |
size() / capacity() | Elements stored / total room before the next resize |
isEmpty() | True if size is 0 |
Vector<String> cities = new Vector<>();
cities.add("Chennai");
cities.add("Pune");
cities.insertElementAt("Delhi", 0);
cities.firstElement(); // "Delhi"
cities.size(); // 3