dir.by  
Поиск >>

Компьютер, программы
→
Java
→
Java (class, interface, collections, etc.)
 class Vector in Java 
посмотрели 1194 раз
обновлено: 7 October 2026
class Vector<E> is an array (in other words, a set of elements).

Any element can be gotten by integer index.

You can add and delete elements.

Vector is fully synchronized (thread-safe).

Vector is the same as ArrayList, and the difference is that Vector is fully synchronized (thread-safe). If not need a thread-safe, it is recommended to use ArrayList because works faster.

Vector
  implements interface List<E> this array, i.e. you can add and remove elements, get an element by index
  Java  
interface List<E> extends SequencedCollection<E>
{
Let's look at Functions >> ...
}
Examples
  Java     Creating a new Java console application ... and write the code
package org.example;
import java.util.Vector;

public class Program {
     public static void main(String[] args)
     {
          Vector<String> myList1 = new Vector<String>();

          // Add an element to the end
          myList1.add("Car");
          // myList1 = ["Car"]

          // Add an element to the end
          myList1.add("House");
          // myList1 = ["Car", "House"]

          // Add an element to the end
          myList1.add("Notebook");
          // myList1 = ["Car", "House", "Notebook"]

          // View item by index
          String elem = myList1.get(1);
          // elem = "House"
          // myList1 = ["Car", "House", "Notebook"]

          // Insert element by index 1
          myList1.add(1, "Airplane");
          // myList1 = ["Car", "Airplane", "House", "Notebook"]

          // Delete item by index
          myList1.remove(1);
          // myList1 = ["Car", "House", "Notebook"]
     }
}
  Kotlin     Creating a new Kotlin console application ... and write the code
import java.util.Vector;

fun main() {

     val myList1 = Vector<String>()

     // добавляем элемент в конец
     myList1.add("Car")
     // myList1 = ["Car"]

     // добавляем элемент в конец
     myList1.add("House")
     // myList1 = ["Car", "House"]

     // добавляем элемент в конец
     myList1.add("Notebook")
     // myList1 = ["Car", "House", "Notebook"]

     // посмотреть элемент по индексу
     val elem = myList1[1]
     // elem = "House"
     // myList1 = ["Car", "House", "Notebook"]

     // вставить элемент по индексу 1
     myList1.add(1, "Airplane")
     // myList1 = ["Car", "Airplane", "House", "Notebook"]

     // удалить элемент по индексу
     myList1.removeAt(1)
     // myList1 = ["Car", "House", "Notebook"]
}
Documentation
  Java  
class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
     @SuppressWarnings("serial") // Conditionally serializable
     protected Object[] elementData;

     protected int elementCount;

     protected int capacityIncrement;

     public Vector(int initialCapacity, int capacityIncrement) {
          super();
          if (initialCapacity < 0)
               throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
          this.elementData = new Object[initialCapacity];
          this.capacityIncrement = capacityIncrement;
     }

     public Vector(int initialCapacity) {
          this(initialCapacity, 0);
     }

     public Vector() {
          this(10);
     }

     public Vector(Collection<? extends E> c) {
          Object[] a = c.toArray();
          elementCount = a.length;
          if (c.getClass() == ArrayList.class) {
               elementData = a;
          } else {
               elementData = Arrays.copyOf(a, elementCount, Object[].class);
          }
     }

     public synchronized void copyInto(Object[] anArray) {
          System.arraycopy(elementData, 0, anArray, 0, elementCount);
     }

     public synchronized void trimToSize() {
          modCount++;
          int oldCapacity = elementData.length;
          if (elementCount < oldCapacity) {
               elementData = Arrays.copyOf(elementData, elementCount);
          }
     }

     public synchronized void ensureCapacity(int minCapacity) {
          if (minCapacity > 0) {
               modCount++;
               if (minCapacity > elementData.length)
                    grow(minCapacity);
          }
     }

     private Object[] grow(int minCapacity) {
          int oldCapacity = elementData.length;
          int newCapacity = ArraysSupport.newLength(oldCapacity,
                    minCapacity - oldCapacity, /* minimum growth */
                    capacityIncrement > 0 ? capacityIncrement : oldCapacity
                    /* preferred growth */);
          return elementData = Arrays.copyOf(elementData, newCapacity);
     }

     private Object[] grow() {
          return grow(elementCount + 1);
     }

     public synchronized void setSize(int newSize) {
          modCount++;
          if (newSize > elementData.length)
               grow(newSize);
          final Object[] es = elementData;
          for (int to = elementCount, i = newSize; i < to; i++)
               es[i] = null;
          elementCount = newSize;
     }

     public synchronized int capacity() {
          return elementData.length;
     }

     public synchronized int size() {
          return elementCount;
     }

     public synchronized boolean isEmpty() {
          return elementCount == 0;
     }

     public Enumeration<E> elements() {
          return new Enumeration<E>() {
               int count = 0;

               public boolean hasMoreElements() {
                    return count < elementCount;
               }

               public E nextElement() {
                    synchronized (Vector.this) {
                         if (count < elementCount) {
                              return elementData(count++);
                         }
                    }
                    throw new NoSuchElementException("Vector Enumeration");
               }
          };
     }

     public boolean contains(Object o) {
          return indexOf(o, 0) >= 0;
     }

     public int indexOf(Object o) {
          return indexOf(o, 0);
     }

     public synchronized int indexOf(Object o, int index) {
          if (o == null) {
               for (int i = index ; i < elementCount ; i++)
                    if (elementData[i]==null)
                         return i;
          } else {
               for (int i = index ; i < elementCount ; i++)
                    if (o.equals(elementData[i]))
                         return i;
          }
          return -1;
     }

     public synchronized int lastIndexOf(Object o) {
          return lastIndexOf(o, elementCount-1);
     }

     public synchronized int lastIndexOf(Object o, int index) {
          if (index >= elementCount)
               throw new IndexOutOfBoundsException(index + " >= "+ elementCount);

          if (o == null) {
               for (int i = index; i >= 0; i--)
                    if (elementData[i]==null)
                         return i;
          } else {
               for (int i = index; i >= 0; i--)
                    if (o.equals(elementData[i]))
                         return i;
          }
          return -1;
     }

     public synchronized E elementAt(int index) {
          if (index >= elementCount) {
               throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
          }
          return elementData(index);
     }

     public synchronized E firstElement() {
          if (elementCount == 0) {
               throw new NoSuchElementException();
          }
          return elementData(0);
     }

     public synchronized E lastElement() {
          if (elementCount == 0) {
               throw new NoSuchElementException();
          }
          return elementData(elementCount - 1);
     }

     public synchronized void setElementAt(E obj, int index) {
          if (index >= elementCount) {
               throw new ArrayIndexOutOfBoundsException(index + " >= " +
                         elementCount);
          }
          elementData[index] = obj;
     }

     public synchronized void removeElementAt(int index) {
          if (index >= elementCount) {
               throw new ArrayIndexOutOfBoundsException(index + " >= " +
                         elementCount);
          }
          else if (index < 0) {
               throw new ArrayIndexOutOfBoundsException(index);
          }
          int j = elementCount - index - 1;
          if (j > 0) {
               System.arraycopy(elementData, index + 1, elementData, index, j);
          }
          modCount++;
          elementCount--;
          elementData[elementCount] = null; /* to let gc do its work */
     }

     public synchronized void insertElementAt(E obj, int index) {
          if (index > elementCount) {
               throw new ArrayIndexOutOfBoundsException(index
                         + " > " + elementCount);
          }
          modCount++;
          final int s = elementCount;
          Object[] elementData = this.elementData;
          if (s == elementData.length)
               elementData = grow();
          System.arraycopy(elementData, index,
                    elementData, index + 1,
                    s - index);
          elementData[index] = obj;
          elementCount = s + 1;
     }

     public synchronized void addElement(E obj) {
          modCount++;
          add(obj, elementData, elementCount);
     }

     public synchronized boolean removeElement(Object obj) {
          modCount++;
          int i = indexOf(obj);
          if (i >= 0) {
               removeElementAt(i);
               return true;
          }
          return false;
     }

     public synchronized void removeAllElements() {
          final Object[] es = elementData;
          for (int to = elementCount, i = elementCount = 0; i < to; i++)
               es[i] = null;
          modCount++;
     }

     public synchronized Object clone() {
          try {
               @SuppressWarnings("unchecked")
               Vector<E> v = (Vector<E>) super.clone();
               v.elementData = Arrays.copyOf(elementData, elementCount);
               v.modCount = 0;
               return v;
          } catch (CloneNotSupportedException e) {
               // this shouldn't happen, since we are Cloneable
               throw new InternalError(e);
          }
     }

     public synchronized Object[] toArray() {
          return Arrays.copyOf(elementData, elementCount);
     }

     @SuppressWarnings("unchecked")
     public synchronized <T> T[] toArray(T[] a) {
          if (a.length < elementCount)
               return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());

          System.arraycopy(elementData, 0, a, 0, elementCount);

          if (a.length > elementCount)
               a[elementCount] = null;

          return a;
     }

     // Positional Access Operations
     @SuppressWarnings("unchecked")
     E elementData(int index) {
          return (E) elementData[index];
     }

     @SuppressWarnings("unchecked")
     static <E> E elementAt(Object[] es, int index) {
          return (E) es[index];
     }

     public synchronized E get(int index) {
          if (index >= elementCount)
               throw new ArrayIndexOutOfBoundsException(index);

          return elementData(index);
     }

     public synchronized E set(int index, E element) {
          if (index >= elementCount)
               throw new ArrayIndexOutOfBoundsException(index);

          E oldValue = elementData(index);
          elementData[index] = element;
          return oldValue;
     }

     private void add(E e, Object[] elementData, int s) {
          if (s == elementData.length)
               elementData = grow();
          elementData[s] = e;
          elementCount = s + 1;
     }

     public synchronized boolean add(E e) {
          modCount++;
          add(e, elementData, elementCount);
          return true;
     }

     public boolean remove(Object o) {
          return removeElement(o);
     }

     public void add(int index, E element) {
          insertElementAt(element, index);
     }

     public synchronized E remove(int index) {
          modCount++;
          if (index >= elementCount)
               throw new ArrayIndexOutOfBoundsException(index);
          E oldValue = elementData(index);

          int numMoved = elementCount - index - 1;
          if (numMoved > 0)
               System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
          elementData[--elementCount] = null; // Let gc do its work

          return oldValue;
     }

     public void clear() {
          removeAllElements();
     }

     // Bulk Operations

     public synchronized boolean containsAll(Collection<?> c) {
          return super.containsAll(c);
     }

     public boolean addAll(Collection<? extends E> c) {
          Object[] a = c.toArray();
          modCount++;
          int numNew = a.length;
          if (numNew == 0)
               return false;
          synchronized (this) {
               Object[] elementData = this.elementData;
               final int s = elementCount;
               if (numNew > elementData.length - s)
                    elementData = grow(s + numNew);
               System.arraycopy(a, 0, elementData, s, numNew);
               elementCount = s + numNew;
               return true;
          }
     }

     public boolean removeAll(Collection<?> c) {
          Objects.requireNonNull(c);
          return bulkRemove(e -> c.contains(e));
     }

     public boolean retainAll(Collection<?> c) {
          Objects.requireNonNull(c);
          return bulkRemove(e -> !c.contains(e));
     }

     @Override
     public boolean removeIf(Predicate<? super E> filter) {
          Objects.requireNonNull(filter);
          return bulkRemove(filter);
     }

     public synchronized boolean addAll(int index, Collection<? extends E> c) {
          if (index < 0 || index > elementCount)
               throw new ArrayIndexOutOfBoundsException(index);

          Object[] a = c.toArray();
          modCount++;
          int numNew = a.length;
          if (numNew == 0)
               return false;
          Object[] elementData = this.elementData;
          final int s = elementCount;
          if (numNew > elementData.length - s)
               elementData = grow(s + numNew);

          int numMoved = s - index;
          if (numMoved > 0)
               System.arraycopy(elementData, index,
                         elementData, index + numNew,
                         numMoved);
          System.arraycopy(a, 0, elementData, index, numNew);
          elementCount = s + numNew;
          return true;
     }

     public synchronized boolean equals(Object o) {
          return super.equals(o);
     }

     public synchronized int hashCode() {
          return super.hashCode();
     }

     public synchronized String toString() {
          return super.toString();
     }

     public synchronized List<E> subList(int fromIndex, int toIndex) {
          return Collections.synchronizedList(super.subList(fromIndex, toIndex),
                    this);
     }

     protected synchronized void removeRange(int fromIndex, int toIndex) {
          modCount++;
          shiftTailOverGap(elementData, fromIndex, toIndex);
     }

     @java.io.Serial
     private void readObject(ObjectInputStream in)
               throws IOException, ClassNotFoundException {
          ObjectInputStream.GetField gfields = in.readFields();
          int count = gfields.get("elementCount", 0);
          Object[] data = (Object[])gfields.get("elementData", null);
          if (count < 0 || data == null || count > data.length) {
               throw new StreamCorruptedException("Inconsistent vector internals");
          }
          elementCount = count;
          elementData = data.clone();
     }

     @java.io.Serial
     private void writeObject(java.io.ObjectOutputStream s)
               throws java.io.IOException {
          final java.io.ObjectOutputStream.PutField fields = s.putFields();
          final Object[] data;
          synchronized (this) {
               fields.put("capacityIncrement", capacityIncrement);
               fields.put("elementCount", elementCount);
               data = elementData.clone();
          }
          fields.put("elementData", data);
          s.writeFields();
     }

     public synchronized ListIterator<E> listIterator(int index) {
          if (index < 0 || index > elementCount)
               throw new IndexOutOfBoundsException("Index: "+index);
          return new ListItr(index);
     }

     public synchronized ListIterator<E> listIterator() {
          return new ListItr(0);
     }

     public synchronized Iterator<E> iterator() {
          return new Itr();
     }

     @Override
     public synchronized void forEach(Consumer<? super E> action) {
          Objects.requireNonNull(action);
          final int expectedModCount = modCount;
          final Object[] es = elementData;
          final int size = elementCount;
          for (int i = 0; modCount == expectedModCount && i < size; i++)
               action.accept(elementAt(es, i));
          if (modCount != expectedModCount)
               throw new ConcurrentModificationException();
     }

     @Override
     public synchronized void replaceAll(UnaryOperator<E> operator) {
          Objects.requireNonNull(operator);
          final int expectedModCount = modCount;
          final Object[] es = elementData;
          final int size = elementCount;
          for (int i = 0; modCount == expectedModCount && i < size; i++)
               es[i] = operator.apply(elementAt(es, i));
          if (modCount != expectedModCount)
               throw new ConcurrentModificationException();
          // TODO(8203662): remove increment of modCount from ...
          modCount++;
     }

     @SuppressWarnings("unchecked")
     @Override
     public synchronized void sort(Comparator<? super E> c) {
          final int expectedModCount = modCount;
          Arrays.sort((E[]) elementData, 0, elementCount, c);
          if (modCount != expectedModCount)
               throw new ConcurrentModificationException();
          modCount++;
     }

     @Override
     public Spliterator<E> spliterator() {
          return new VectorSpliterator(null, 0, -1, 0);
     }
}
Learn more about methods in the Java documentation:https://docs.oracle.com ...
 
← Previous topic
class ArrayList<E> in Java
 
Next topic →
class Stack<E> in Java
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

 
Download and install
• Installation JDK (download and install the Java library for Windows)
• Download and install IntelliJ IDEA to explore Java, Spring, Jakarta EE | Functionality and differences: Community | Ultimate
• Error "JDK is missing" | Java
Java (class, interface, collections, etc.)
• Create a simple console app in IntelliJ IDEA to learn Java
• Access modifiers (private, protected, public) for a class and for methods and fields. | Java
• Collections in Java
• interface List<E> in Java
• class ArrayList<E> in Java
• class Vector<E> in Java
• class Stack<E> in Java
• class CopyOnWriteArrayList<E> in Java
• interface Queue<E> in Java
• interface Deque<E> in Java
• class LinkedList<E> in Java
• interface Set in Java
• class HashSet<E> in Java
• class LinkedHashSet<E> in Java
• Collections.singletonList("Hello") returns an immutable list containing exactly one specified element | Java collection
• class Collections (all functions, algorithms) | Java
• stream.filter(...) select elements according to your criterion | Java collection | Example: allCars.stream().filter(item -> item.Price < 30000).toList()
• What is interface in Java ?
• Directly in the code (at runtime) we make an implementation for the interface | Java
• Threads in Java
• lambda is an unnamed method (no name and no class owned) | Java
• Exceptions and handling in Java. Example: try {...} catch (Exception e) {...}
• Why use throws Exception in the function name in Java? Answer: The method throws an exception and there is no handling of try catch. Example: float CalculateDensity(float mass, float volume) throws Exception { ... throw new Exception("Error! Volume is zero."); ... }
Java web application (servlet, jsp page, basic functionality and no frameworks)
• Creating a new simple web application (jsp web page) | Java, Maven
• Create a web servlet (the servlet is located on the web server, returns the result on request) | Java
• Installation Tomcat web server (download and install for Windows)
• Check, test Tomcat web server (create a new my.hml file)
• What is Maven
• What is a dynamic web page jsp (Java Server Page) ?
• How to install Smart Tomcat plugin in Intellij Idea
• Error "The SDK is not specified for module ... | Project SDK is not defined ..." in IntelliJ IDEA | Java
Spring in Java (Spring Framework, Spring Data, Spring Boot, ...)
• What is Spring? Why use Spring in Java?
• What is Spring Bean? What is Spring Container? IoC (inversion of control) | Creating a simple Spring project and configuration Spring Container in an XML file | Editor IntelliJ Idea and language Java
• What is Dependency Injection in Spring? Creating a simple Spring project with Dependency Injection in the constructor with the attributes @Component, @Autowired | Editor IntelliJ Idea and language Java
• Create a new Spring Web application (the request goes to the Controller → Controller creates a response as text or json) | Java, Spring Web, Spring Boot, Maven
• Creating a new Spring WebSocket application (Java WebSocket sends a message to the JavaScript WebSocket) | Java, Spring WebSocket, Spring Boot, Maven
• Create Azure Web App with the type Java (free). That is, create an empty web server
• Put the Java Spring web application in Azure
• Connect to the application Azure Web App (Java) via FTP | use File Explorer
• Error "The SDK is not specified for module ... | Project SDK is not defined ..." in IntelliJ IDEA | Java, Spring Boot
• How to install Spring WebSocket plugin in Intellij Idea
Jakarta EE / Java EE in Java (Web Applications, Web Services)
• What is Jakarta EE (Java EE)? | In which editor (program) is it convenient to write Jakarta EE (Java EE) code?
• Creating a simple web project in IntelliJ Idea Ultimate | Jakarta EE (Java EE)
Struts in Java (extends API Java Servlet using MVC)
• What is Struts | Java
Courses, training
• Course "Java developer" from Yandex
Interview
• Interviews on Java

  Ваши вопросы присылайте по почте: info@dir.by