← Назад к вопросам
Насколько увеличится Vector при добавлении 11-го элемента при заданных 10 элементах
1.0 Junior🔥 141 комментариев
#Коллекции
Комментарии (1)
🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
Насколько увеличится Vector при добавлении 11-го элемента?
Краткий ответ
Vector увеличится ровно на 10 элементов (в два раза). При добавлении 11-го элемента в Vector с 10 элементами, capacity увеличится с 10 до 20, так как Vector использует стратегию удвоения ёмкости (doubling).
Что такое Vector в Java?
Vector — это синхронизированный (thread-safe) аналог ArrayList. Это наследник класса AbstractList и реализует List интерфейс.
public class Vector<E> extends AbstractList<E> {
// elementData - массив для хранения элементов
protected Object[] elementData;
// elementCount - текущее количество элементов
protected int elementCount;
// capacityIncrement - на сколько увеличивать при нехватке места
protected int capacityIncrement;
}
Ёмкость vs Размер (Capacity vs Size)
Важно различать два понятия:
Vector<String> vector = new Vector<>();
// Конструктор по умолчанию
// Capacity = 10 (начальная ёмкость)
// Size = 0 (текущее количество элементов)
System.out.println(vector.capacity()); // 10
System.out.println(vector.size()); // 0
// Добавим 10 элементов
for (int i = 0; i < 10; i++) {
vector.add("Element " + i);
}
System.out.println(vector.capacity()); // 10
System.out.println(vector.size()); // 10
// Добавим 11-й элемент
vector.add("Element 10");
// Теперь:
System.out.println(vector.capacity()); // 20 (увеличилось в два раза!)
System.out.println(vector.size()); // 11
Как происходит увеличение
1. Конструктор по умолчанию
public Vector() {
this(10); // Начальная ёмкость = 10
}
public Vector(int initialCapacity) {
this(initialCapacity, 0); // capacityIncrement = 0
}
public Vector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement; // 0 по умолчанию!
}
2. Метод ensureCapacity (внутренний)
private void ensureCapacityHelper(int minCapacity) {
Object[] elementData = this.elementData;
// Если текущей ёмкости недостаточно
if (minCapacity - elementData.length > 0) {
grow(minCapacity); // увеличить ёмкость
}
}
private Object[] grow(int minCapacity) {
int oldCapacity = elementData.length;
// Если capacityIncrement > 0, увеличиваем на capacityIncrement
// Иначе удваиваем ёмкость
int newCapacity = oldCapacity +
((capacityIncrement > 0) ? capacityIncrement : oldCapacity);
// newCapacity = 10 + ((0 > 0) ? 0 : 10) = 10 + 10 = 20
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
return elementData = Arrays.copyOf(elementData, newCapacity);
}
3. Пошаговый процесс
Шаг 1: Создание Vector
┌─────────────────────────────────┐
│ Vector v = new Vector(); │
│ capacity = 10, size = 0 │
│ elementData = [_, _, _, ...] │ (10 ячеек)
└─────────────────────────────────┘
Шаг 2: Добавление элементов 0-9
┌─────────────────────────────────┐
│ for (i = 0; i < 10; i++) │
│ v.add("Element " + i); │
│ capacity = 10, size = 10 │
│ elementData = [E0, E1, ..., E9] │ (10 ячеек, все заняты)
└─────────────────────────────────┘
Шаг 3: Добавление 11-го элемента
┌──────────────────────────────────────────────────┐
│ v.add("Element 10"); │
│ │
│ 1. Проверка: size (10) >= capacity (10)? ДА │
│ 2. Вызов grow(11) │
│ 3. newCapacity = 10 + 10 = 20 │
│ 4. Создание нового массива[20] │
│ 5. Копирование всех 10 элементов в новый массив│
│ 6. Добавление 11-го элемента │
│ │
│ capacity = 20, size = 11 │
│ elementData = [E0, ..., E10, _, _, ...] │
└──────────────────────────────────────────────────┘
Различные конструкторы Vector
// 1. По умолчанию (capacityIncrement = 0)
Vector<String> v1 = new Vector<>();
// capacity = 10, удваивается: 10 -> 20 -> 40 -> 80 ...
// 2. С заданной начальной ёмкостью
Vector<String> v2 = new Vector<>(5);
// capacity = 5, удваивается: 5 -> 10 -> 20 -> 40 ...
// 3. С capacityIncrement
Vector<String> v3 = new Vector<>(10, 5);
// capacity = 10, увеличивается на 5: 10 -> 15 -> 20 -> 25 ...
// 4. Из Collection
Vector<String> v4 = new Vector<>(Arrays.asList("a", "b", "c"));
// capacity = 3, удваивается: 3 -> 6 -> 12 ...
Демонстрация на примере
public class VectorCapacityExample {
public static void main(String[] args) {
Vector<Integer> vector = new Vector<>();
// Начальная ёмкость
System.out.println("Initial capacity: " + vector.capacity()); // 10
System.out.println("Initial size: " + vector.size()); // 0
// Добавляем элементы и отслеживаем ёмкость
for (int i = 0; i < 25; i++) {
if (vector.size() == vector.capacity()) {
System.out.println("Before adding element " + i +
": capacity = " + vector.capacity());
}
vector.add(i);
if (vector.size() == vector.capacity()) {
System.out.println("After adding element " + i +
": capacity = " + vector.capacity());
}
}
}
}
// Вывод:
// Initial capacity: 10
// Initial size: 0
// Before adding element 10: capacity = 10
// After adding element 10: capacity = 20
// Before adding element 20: capacity = 20
// After adding element 20: capacity = 40
Сравнение с ArrayList
// ArrayList имеет похожую логику, но немного другую
public class ArrayList<E> {
private static final int DEFAULT_CAPACITY = 10;
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
// ArrayList увеличивает на 50%: oldCapacity + (oldCapacity >> 1)
int newCapacity = oldCapacity + (oldCapacity >> 1); // oldCapacity * 1.5
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
Vector<String> vector = new Vector<>();
// 10 -> 20 -> 40 -> 80 (удваивается)
ArrayList<String> arrayList = new ArrayList<>();
// 10 -> 15 -> 22 -> 33 (увеличивается на 50%)
С capacityIncrement > 0
// Vector с capacityIncrement = 5
Vector<String> vector = new Vector<>(10, 5);
// Ёмкость будет увеличиваться на 5:
// 10 (начально)
// + 5 элементов -> 15
// + 5 элементов -> 20
// + 5 элементов -> 25
// ...
System.out.println(vector.capacity()); // 10
for (int i = 0; i < 20; i++) {
vector.add("Element " + i);
if (i == 9 || i == 14 || i == 19) {
System.out.println("After adding element " + i +
": capacity = " + vector.capacity());
}
}
// Вывод:
// After adding element 9: capacity = 15
// After adding element 14: capacity = 20
// After adding element 19: capacity = 25
Почему Vector устарел?
// Vector синхронизирован по ВСЕМУ объекту
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
public synchronized E get(int index) {
return get(index);
}
// Это неэффективно - нельзя читать из разных потоков параллельно
// ArrayList не синхронизирован, но безопаснее использовать
List<String> list = Collections.synchronizedList(new ArrayList<>());
Итоговая таблица
| Параметр | Vector (по умолчанию) | ArrayList | CopyOnWriteArrayList |
|---|---|---|---|
| Начальная ёмкость | 10 | 10 | 0 |
| Стратегия увеличения | x2 (удвоение) | x1.5 (50%) | x2 (удвоение) |
| Синхронизирован | Да (весь объект) | Нет | Да (copy-on-write) |
| Современное использование | Редко | Обычно | Если много чтений |
Конкретный ответ на вопрос
При добавлении 11-го элемента в Vector с 10 элементами:
До добавления:
- capacity = 10
- size = 10
После добавления:
- capacity = 20 (увеличилось на 10, т.е. в два раза)
- size = 11
Увеличение = 20 - 10 = 10 элементов