Progress-servis55.ru

Новости из мира ПК
7 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java util vector

Java.util.Vector Class

Introduction

The java.util.Vector class implements a growable array of objects. Similar to an Array, it contains components that can be accessed using an integer index. Following are the important points about Vector −

The size of a Vector can grow or shrink as needed to accommodate adding and removing items.

Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement.

As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface.

Unlike the new collection implementations, Vector is synchronized.

This class is a member of the Java Collections Framework.

Class declaration

Following is the declaration for java.util.Vector class −

Here represents an Element, which could be any class. For example, if you’re building an array list of Integers then you’d initialize it as follows −

>

Sr.No.Constructor & Description1

This constructor is used to create an empty vector so that its internal data array has size 10 and its standard capacity increment is zero.

This constructor is used to create a vector containing the elements of the specified collection, in the order they are returned by the collection’s iterator.

This constructor is used to create an empty vector with the specified initial capacity and with its capacity increment equal to zero.

Vector(int initialCapacity, int capacityIncrement)

This constructor is used to create an empty vector with the specified initial capacity and capacity increment.

>

Sr.No.Method & Description1boolean add(E e)

This method appends the specified element to the end of this Vector.

This method inserts the specified element at the specified position in this Vector.

This method appends all of the elements in the specified Collection to the end of this Vector.

This method inserts all of the elements in the specified Collection into this Vector at the specified position.

This method adds the specified component to the end of this vector, increasing its size by one.

This method returns the current capacity of this vector.

This method removes all of the elements from this vector.

This method returns a clone of this vector.

This method returns true if this vector contains the specified element.

This method returns true if this Vector contains all of the elements in the specified Collection.

This method copies the components of this vector into the specified array.

This method returns the component at the specified index.

This method returns an enumeration of the components of this vector.

This method increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.

This method compares the specified Object with this Vector for equality.

This method returns the first component (the item at index 0) of this vector.

This method returns the element at the specified position in this Vector.

This method returns the hash code value for this Vector.

This method returns the index of the first occurrence of the specified element in this vector, or -1 if this vector does not contain the element.

This method returns the index of the first occurrence of the specified element in this vector, searching forwards from index, or returns -1 if the element is not found.

This method inserts the specified object as a component in this vector at the specified index.

This method tests if this vector has no components.

This method returns the last component of the vector.

This method returns the index of the last occurrence of the specified element in this vector, or -1 if this vector does not contain the element.

This method returns the index of the last occurrence of the specified element in this vector, searching backwards from index, or returns -1 if the element is not found.

This method removes the element at the specified position in this Vector.

This method removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged.

This method removes from this Vector all of its elements that are contained in the specified Collection.

This method removes all components from this vector and sets its size to zero.

This method removes the first occurrence of the argument from this vector.

This method deletes the component at the specified index.

This method removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.

This method retains only the elements in this Vector that are contained in the specified Collection.

This method replaces the element at the specified position in this Vector with the specified element.

This method sets the component at the specified index of this vector to be the specified object.

This method sets the size of this vector.

This method returns the number of components in this vector.

This method returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive.

This method returns an array containing all of the elements in this Vector in the correct order.

This method returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array.

This method returns a string representation of this Vector, containing the String representation of each element.

This method trims the capacity of this vector to be the vector’s current size.

Methods inherited

This class inherits methods from the following classes −

Библиотека примеров приложений Java

Оглавление
Базовые типы

Замещающие типы
Без указателей
Массивы
Структурное программи-
рование

Обработка исключений
Возбуждение исключений
Классы обработки исключений
Блок finally
Строки String
Класс Math
Класс Vector
Класс Stack
Словарь на базе Hashtable
Словарь на базе Properties
Цифровые часы
Собственный класс
Наследование классов

Интерфейсы

1.12. Использование класса Vector

В примере демонстрируются некоторые приемы работы с объектами класса Vector, предназначенного для создания массивов переменного размера.

Немного теории

Часто перед программистом встает задача организации массива с неизвестным заранее размером. Стандартные массивы в Java не подходят для решения этой задачи, так как их размер должен быть указан в исходном тексте программы явным образом при выделении памяти.

Для организации массива с динамически изменяющимся размером вы можете воспользоваться классом java.util.Vector. Такой массив может хранить объекты любого класса.

При создании объекта класса Vector размер соответствующего массива можно не указывать. В этом случае будет создан массив с размером, принятом по умолчанию. Когда вы будете добавлять в него новые элементы, размер массива при необходимости будет автоматически увеличиваться.

Выбрав соответствующий конструктор, программист может задать как начальный размер массива, так и величину, на которую происходит увеличение этого размера.

С помощью методов, определенных в классе Vector, вы можете добавлять в массив новые элементы (как в конец массива, так и в произвольную ячейку со сдвигом остальных ячеек), извлекать элемент по номеру ячейки, выполнять поиск, удаление элементов и так далее.

Описание примера

В нашем примере мы создаем массив vPoints как объект класса Vector, предназначенный для хранения объектов класса MyPoint. Класс MyPoint предназначен для работы с точками, представленными своими координатами.

Массив vPoints создается следующим образом:

Далее программа запрашивает у пользователя начальный размер массива:

Здесь мы читаем строку символов из стандартного потока ввода методом System.in.read, удаляем из нее символы возврата каретки и перевода строки, а затем создаем объект класса Integer, передавая введенную и обработанную строку конструктору. Далее методом intValue мы преобразуем число к типу int и записываем его в переменную j.

На следующем шаге мы добавляем j элементов в массив:

Для добавления применяется метод addElement, определенный в классе Vector. В качестве параметра мы передаем этому методу ссылку на объект класса MyPoint, созданный с помощью оператора new.

В качестве координаты точки по оси X мы указываем конструктору класса MyPoint номер элемента массива, а в качестве координаты по оси Y — тот же номер, увеличенный на 10.

В следующем фрагменте кода мы демонстрируем использование методов insertElementAt и setElementAt:

Первый из них предназначен для вставки в массив нового элемента со сдвигом остальных в сторону конца массива, а второй — для замещения содержимого заданной ячейки массива. В обоих случаях новый элемент передается через первый параметр, а номер ячейки — через второй.

Если текущий размер массива меньше указанного номера ячейки, возникает исключение ArrayIndexOutOfBoundsException. Мы предусмотрели его обработку в блоке catch.

После заполнения массива программа выводит его содержимое на консоль.

Размер массива мы получаем с помощью метода size, определенного в классе Vector:

Для извлечения элемента из массива мы применяем метод elementAt, передавая ему номер извлекаемого элемента. Этот метод возвращает ссылку на извлеченный объект. Преобразовав ссылку к типу MyPoint, мы распечатываем координаты точки, вызывая для этого метод printPoint, определенный в классе MyPoint.

Вот что мы увидим на консоли, указав начальный размер массива, равный 10:

Обратите внимание, что записи отображаются в том порядке, в котором они были добавлены в массив. Точка с координатами (2000, 2000) была вставлена после того как цикл заполнения массива завершил свою работу. Четвертый по порядку элемент (имеющий индекс, равный трем) был заменен.

Реализация класса MyPoint достаточно проста:

В нем определен конструктор и два метода. Конструктор и метод setPoint позволяют указывать координаты точки. Метод printPoint выводит эти координаты на консоль.

29.4. Java – Класс Vector

Класс Vector – реализует динамический массив. Он схож с ArrayList, но с двумя отличиями:

  • Vector синхронизируется.
  • Vector содержит множество устаревших методов, которые не являются частью структуры коллекций.

В Java класс Vector оказывается очень полезным, если вы заранее не знаете размер массива или вам нужен такой массив, который может менять размеры за время работы программы.

Содержание

Конструкторы

Далее приведён список конструкторов, предоставленные классом Vector в Java.

Конструктор и описание
1Vector()
Этот конструктор создаёт стандартный вектор, начальный размер которого равен 10.
2Vector(int size)
Этот конструктор принимает аргумент, который равен необходимому размеру, и создаёт вектор, начальная вместимость которого определяется size.
3Vector(int size, int incr)
Этот конструктор создает вектор, начальная вместимость которого определяется size и инкремент которого определяется incr. Инкремент указывает количество элементов, которые будут выделяться каждый раз, когда вектор изменяется в размерах.
4Vector(Collection c)
Этот конструктор создаёт вектор, который содержит элементы из коллекции c.

Методы

Помимо методов, унаследованных из их родительных классов, Vector в Java определяет следующие методы:

Метод и описание
1void add(int index, Object element)
Вставляет указанный элемент в указанное положение в этом Vector.
2boolean add(Object o)
Добавляет указанный элемент в конец этого вектора Vector.
3boolean addAll(Collection c)
Добавляет все элементы в указанной коллекции в конец этого Vector в том порядке, в котором они возвращаются итератором коллекции.
4boolean addAll(int index, Collection c)
Вставляет все элементы в указанной коллекции в этот Vector в указанной позиции.
5void addElement(Object obj)
Добавляет указанный компонент в конец этого вектора, увеличивая его размер на единицу.
6int capacity()
Возвращает текущую вместимость этого вектора.
7void clear()
Удаляет все компоненты в этом векторе.
8Object clone()
Возвращает клон этого вектора.
9boolean contains(Object elem)
Проверяет, является ли указанный объект компонентом этого вектора.
10boolean containsAll(Collection c)
Возвращает true, если этот вектор содержит все элементы в указанной Коллекции.
11void copyInto(Object[] anArray)
Копирует компоненты этого вектора в указанный массив.
12Object elementAt(int index)
Возвращает компонент в под указанным индексом.
13Enumeration elements()
Возвращает перечисление компонентов этого вектора.
14void ensureCapacity(int minCapacity)
Увеличивает вместимость этого вектора, если это необходимо, чтобы обеспечить возможность удержания как минимум количества компонентов, указанное аргументом минимальной вместимости.
15boolean equals(Object o)
Сравнивает указанный объект с этим вектором для равенства.
16Object firstElement()
Возвращает первый компонент (элемент с нулевым индексом) этого вектора.
17Object get(int index)
Возвращает элемент под указанной позицией в этом векторе.
18int hashCode()
Возвращает значение хэш-кода для этого вектора.
19int indexOf(Object elem)
Ищет первое появление данного аргумента, проверяет равенство, используя метод equals.
20int indexOf(Object elem, int index)
Ищет первое появление данного аргумента, начиная поиск с указанного индекса, и проверяет равенство, используя метод equals.
21void insertElementAt(Object obj, int index)
Вставляет указанный объект как компонент в этот вектор под указанным индексом.
22boolean isEmpty()
Проверяет, является ли вектор пустым (без компонентов).
23Object lastElement()
Возвращает последний компонент вектора.
24int lastIndexOf(Object elem)
Возвращает индекс последнего появления указанного объекта в этом векторе.
25int lastIndexOf(Object elem, int index)
Ищет последний указанный объект, начиная с указанного индекса, и возвращает ему индекс.
26Object remove(int index)
Удаляет элемент под указанной позицией в этом векторе.
27boolean remove(Object o)
Удаляет первое появление указанного элемента в этом векторе. Если вектор не содержит этот элемент, он остаётся неизменённым.
28boolean removeAll(Collection c)
Удаляет из этого вектора все его компоненты, которые содержаться в указанной коллекции.
29void removeAllElements()
Удаляет все компоненты из этого вектора и задаёт ему размер, равный нулю.
30boolean removeElement(Object obj)
Удаляет первое (с наименьшим индексом) появление аргумента в этом векторе.
31void removeElementAt(int index)
Удаляет появление аргумента в этом векторе.
32protected void removeRange(int fromIndex, int toIndex)
Удаляет из этого списка все элементы, индекс которых между fromIndex, включительно, и toIndex, исключительно.
33boolean retainAll(Collection c)
Сохраняет только элементы этого вектора, которые содержатся в указанной коллекции.
34Object set(int index, Object element)
Заменяет элемент под указанной позицией в этом векторе на указанный элемент.
35void setElementAt(Object obj, int index)
Устанавливает компонент под указанным индексом этого вектора как заданный объект.
36void setSize(int newSize)
Устанавливает размер этого вектора.
37int size()
Возвращает количество компонентов в этом векторе.
38List subList(int fromIndex, int toIndex)
Возвращает вид части этого списка между fromIndex, включительно, и toIndex, исключительно.
39Object[] toArray()
Возвращает массив, содержащий все элементы в этом векторе в правильном порядке.
40Object[] toArray(Object[] a)
Возвращает массив, содержащий все элементы в этом векторе в правильном порядке; тип выполнения возвращаемого массива – тип указанного массива.
41String toString()
Возвращает строковое представление этого вектора, содержащее строковое представление каждого элемента.
42void trimToSize()
Уменьшает вместимость этого вектора до текущего размера вектора.

Пример

Следующая программа показывает несколько методов, поддерживаемых этой коллекцией:

Differences between std::vector and java.util.Vector

In C++ i can insert an item into an arbitrary position in a vector, just like the code below:

In Java i can not do the same, i get an exception java.lang.ArrayIndexOutOfBoundsException, code below:

It means that C++ is better designed or is just a Java design decision ? Why java use this approach ?

3 Answers 3

You are creating a vector of size 10. So all indexes from 0 to 9 are valid afterwards.

In the Java code:

You are creating an empty vector with an initial capacity of 10. It means the underlying array is of size 10 but the vector itself has the size 0.

It does not mean one is better designed than the other. The API is just different and this is not a difference that makes one better than the other.

Note that in Java it is now preffered to use ArrayList , which has almost the same API, but is not synchronized. If you want to find a bad design decision in Java’s Vector, then this synchronization on every operation was probably one.

Therefore the best way to write an equivalent of the C++ initialization code in Java is :

The Javadoc for Vector.add(int, Object) pretty clearly states that an IndexOutOfBoundsException will be thrown if the index is less than zero or greater than or equal to the size. The Vector type grows as needed, and the constructor you’ve used sets the initial capacity, which is different than the size. Please read the linked Javadoc to better understand how to use the Vector type. Also, we java developers typically use a List type, such as ArrayList in situations where you would generally use a std::vector in C++.

Differences? You cannot compare how 2 languages do those. Normally Vector do use Stack data structure or LinkedList (or may be both). Which means, you put one item to the top, put another item on top of it, another item even on top of it, like wise. In LinkedList, it is bit different, you «pull» the value but the same thing. So in C++ it is better to use push_back() method.

C++ Vector objects are instantiated automatically. But in Java it is not, you have to fill it. I disagree with the way of filling it using l5.add(1, «Test»); . Use l5.add(«test») .

Since you asked differences, you can define your object in this way as well

That is without a type, in Java we call it without Generics . Possible since Java 1.6

Vector is now not widely used in Java. It has delays. We now move with ArrayList which is inside List interface.

Edit

variable names such as l5 are widely used in C++. But Java community expects more meaningful variable names 🙂

голоса
Рейтинг статьи
Читать еще:  Случайные ошибки измерения подчинены нормальному закону
Ссылка на основную публикацию
Adblock
detector