{"id":7913,"date":"2025-02-07T13:35:33","date_gmt":"2025-02-07T13:35:33","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=7913"},"modified":"2026-04-01T11:56:29","modified_gmt":"2026-04-01T11:56:29","slug":"java-vector","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-vector\/","title":{"rendered":"Java Vector: data structure and Vector class (dynamic array) in Java"},"content":{"rendered":"<p>As part of our series on data structures (collections), we introduce <strong>Java Vector<\/strong> for easier data manipulation. As part of our series on <a href=\"https:\/\/msgprogramator.sk\/en\/data-structures\/\">data structures,<\/a> we&#8217;ll introduce each structure, collection, and class by showing their uses, available methods, advantages and disadvantages, and providing tips on when to use them.<\/p>\n<p>In today&#8217;s section, we will focus on a collection that represents a dynamic array of objects and can increase or decrease its size according to the needs of the application &#8211; <strong>Vector<\/strong>.<\/p>\n<figure id=\"attachment_5121\" aria-describedby=\"caption-attachment-5121\" style=\"width: 300px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-5120 size-medium\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/hierarchia-dedicnosti-kolekcia-vector-1-300x291.webp\" alt=\"Hierarchy of inheritance for the Vector collection\" width=\"300\" height=\"291\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/hierarchia-dedicnosti-kolekcia-vector-1-300x291.webp 300w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/hierarchia-dedicnosti-kolekcia-vector-1-1024x995.webp 1024w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/hierarchia-dedicnosti-kolekcia-vector-1-768x746.webp 768w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/hierarchia-dedicnosti-kolekcia-vector-1.webp 1291w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><figcaption id=\"caption-attachment-5121\" class=\"wp-caption-text\">Hierarchy of inheritance for the Vector collection<\/figcaption><\/figure>\n<h2>Java Vector: introducing the \u201cdynamic object array\u201d data structure in Java<\/h2>\n<p>Programmers often work with static or dynamic arrays. However, these are fixed and can only store a predetermined number of elements. If the storage capacity of an array is exceeded, we most often have to create a new array &#8211; much larger, copy the elements from the old array into it, and delete the old array so that it doesn&#8217;t take up memory space unnecessarily.<\/p>\n<p>And this is what the Vector collection, which automates the whole process in the background, does away with from the programmer&#8217;s point of view. <strong>Vector is flexibly enlarged when more elements are added to it<\/strong> than its current capacity. If it runs out of capacity to store new elements, the new capacity is calculated as twice the old capacity (assuming the <a href=\"https:\/\/msg-life.sk\/praca\/programator\/\">programmer<\/a> doesn&#8217;t set a custom <em>capacityIncrement<\/em> increment).<\/p>\n<p>What is also interesting about this dynamic list is that it can contain objects of different data types.<\/p>\n<p><strong>The Vector class<\/strong> was introduced in Java 1.2 and is found in <strong>the <em>java.util<\/em> package<\/strong>. Although it is currently <strong>less used than the similar ArrayList collection<\/strong>, directly in its implementation Vector is synchronized, that is, only one thread can access a given area at a time, while other threads must wait. This feature makes it particularly suitable for use in multithreaded applications.<\/p>\n<h2>Java Vector &#8211; constructors<\/h2>\n<p>To create a Vector instance, we can use one of four constructors.<\/p>\n<p>1. Creates an empty vector with capacity 10 (default value)<\/p>\n<pre><code class=\"language-java\" data-line=\"\">Vector&lt;E&gt; vector = new Vector&lt;E&gt;();<\/code><\/pre>\n<p>2. Empty vector with initial capacity <em>size<\/em><\/p>\n<pre><code class=\"language-java\" data-line=\"\">Vector&lt;E&gt; vector = new Vector&lt;E&gt;(int size);<\/code><\/pre>\n<p>3. Empty vector with initial capacity <em>size<\/em> and increment <em>capacityIncrement<\/em><\/p>\n<p>The capacity is incremented by <em>capacityIncrement<\/em> when the current capacity is exceeded.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">Vector&lt;E&gt; vector = new Vector&lt;E&gt;(int size, int capacityIncrement);<\/code><\/pre>\n<p>4. Vector constructed using <em>collection<\/em><\/p>\n<p>Initializes the vector with elements from the given collection.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">Vector&lt;E&gt; vector = new Vector&lt;E&gt;(Collection&lt;E&gt; collection);<\/code><\/pre>\n<h2>Java Vector &#8211; basic operations<\/h2>\n<p>The basic operations with the Vektor collection include:<\/p>\n<ul>\n<li>adding elements (one at a time, in bulk),<\/li>\n<li>updating or replacing elements,<\/li>\n<li>removal of elements (by index or value),<\/li>\n<li>accessing elements,<\/li>\n<li>iterate through a collection using for or for-each<\/li>\n<li>element search,<\/li>\n<li>sorting of elements.<\/li>\n<\/ul>\n<h3>Adding elements<\/h3>\n<p>Adding elements to the vector can be done individually or in bulk.<\/p>\n<p><strong>Adding one element<\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">vector.add(&quot;Have&quot;);<\/code><\/pre>\n<p><strong>Adding multiple elements at once<\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">vector.addAll(List.of(&quot;a&quot;, &quot;wonderful&quot;, &quot;day&quot;));<\/code><\/pre>\n<p><strong>Inserting an element on the index<\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">vector.add(1, &quot;all&quot;);<\/code><\/pre>\n<h3>Update or replace elements<\/h3>\n<p>We can update the element using the index using the set() method. This also returns the original element.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">vector.set(3, &quot;year&quot;);\nvector.set(1, &quot;successful&quot;);\n<\/code><\/pre>\n<h3>Removal of elements<\/h3>\n<p>We can remove elements based on their index or by value. Only the first occurrence of an item is always deleted.<\/p>\n<p><strong>Removal by value<\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">vector.remove(&quot;a&quot;);<\/code><\/pre>\n<p><strong>Delete an element by its index<\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">vector.remove(1);<\/code><\/pre>\n<p>All elements to the right of the removed element are moved one position to the left.<\/p>\n<p><strong>Removal of all elements<\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">vector.removeAll();<\/code><code class=\"language-java\" data-line=\"\"><\/code><\/pre>\n<h3>Access to the element<\/h3>\n<p>To get an element of a vector at a particular index, call the get() method.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">String firstElement = vector.get(0);<\/code><\/pre>\n<p>If we provide the get method with an index outside the range of the vector we get an <em>ArrayIndexOutOfBoundsException<\/em>.<\/p>\n<h3>Traversal (iteration) through a vector<\/h3>\n<p><strong>Using a for loop <\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">for (int i = 0; i &lt; vector.size(); i++) {\n    System.out.println(vector.get(i));\n}<\/code><\/pre>\n<p><strong>Using for-each <\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">for (String element : vector) {\n    System.out.println(element);\n}<\/code><\/pre>\n<h3>Search for an element<\/h3>\n<p>If we are interested in whether an element already exists in the vector we can use the contains() call.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">boolean contains = vector.contains(&quot;Have&quot;);<\/code><\/pre>\n<p>In the same way we can get the index of an element, i.e. its position in the vector.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">int index = vector.indexOf(&quot;year&quot;);<\/code><\/pre>\n<p>If the method returns -1, the element was not found in the vector.<\/p>\n<h3>Vector sorting<\/h3>\n<p>If we need to sort a vector, we can do so using the sort() method, which expects a <em>Comparator<\/em> object as input. At this point it is important to mention that the sorting algorithm does not guarantee stability, that is, it does not preserve the relative order of the same elements on the input.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">vector.sort(Comparator.naturalOrder());<\/code><\/pre>\n<h2>Other operations for dynamic object array (Vector)<\/h2>\n<p>I will mention a few other useful methods.<\/p>\n<p><strong>Copy to array <\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">Object[] array = vector.toArray();<\/code><\/pre>\n<p><strong>Deleting all elements<\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">vector.clear();<\/code><\/pre>\n<p><strong>Determination of capacity and vector size <\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">int capacity = vector.capacity();\nint size = vector.size();<\/code><\/pre>\n<p><strong>Index of the last occurrence of the element <\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">vector.lastIndexOf(&quot;year&quot;);<\/code><\/pre>\n<h2>Documentation<\/h2>\n<p>For a complete overview of all available methods for Vector see <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/23\/docs\/api\/java.base\/java\/util\/Vector.html#method-summary\" target=\"_blank\" rel=\"nofollow noopener\">Oracle.<\/a><\/p>\n<h2>Java Vector advantages<\/h2>\n<ul>\n<li><u>The dynamic range<\/u> will take care of storing as many elements as needed.<\/li>\n<li><u>Vector synchronization<\/u> enables use in a multi-threaded environment.<\/li>\n<li><u>Support for legacy Java applications<\/u> that still run on legacy APIs.<\/li>\n<li>Allows adding null elements.<\/li>\n<\/ul>\n<h2>Java Vector disadvantages<\/h2>\n<ul>\n<li><u>Weaker performance<\/u> compared to other collection classes such as ArrayList due to synchronization.<\/li>\n<li>Considered outdated in modern development<\/li>\n<\/ul>\n<h2>When to use Java Vector<\/h2>\n<p>The Vector data structure can be used if we need a scalable collection according to the number of elements we are inserting, but we don&#8217;t know the exact number of elements. It can also be used as a synchronized collection in a multi-threaded application where multiple threads write data to the same structure.<\/p>\n<p>For modern applications, we recommend using <em>ArrayList<\/em> together with manual synchronization (e.g. using Collections.synchronizedList) to ensure consistency and correctness of data during parallel processing.<\/p>\n<h2>Example of using the dynamic Vector object array in a Java program<\/h2>\n<p>Now that we know the basic methods for the Vector collection, we can play around with them a bit in the following program that dynamically modifies a group of strings. First, we create one string and then transform it into another using the methods we&#8217;ve learned.<\/p>\n<pre><code class=\"language-java\" data-line=\"\">import java.util.List;\nimport java.util.Vector;\n\npublic class Main {\n    public static void main(String[] args) {\n        Vector&lt;String&gt; vector = new Vector&lt;&gt;();\n        vector.add(&quot;Have&quot;);\n        vector.addAll(List.of(&quot;a&quot;, &quot;wonderful&quot;, &quot;day&quot;));\n        System.out.println(String.join(&quot; &quot;, vector));\n        vector.set(0, &quot;Happy&quot;);\n        vector.remove(&quot;a&quot;);\n        vector.set(1, &quot;new&quot;);\n        vector.set(2, &quot;year&quot;);\n        vector.add(&quot;2025&quot;);\n        System.out.println(String.join(&quot; &quot;, vector));\n    }\n}<\/code><code class=\"language-java\" data-line=\"\"><\/code><\/pre>\n<p><strong>The output of this example is:<\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-5024\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/02\/vystup-prikladu-vector.webp\" alt=\"Output from the Main.java Vector example \" width=\"287\" height=\"116\" \/><\/p>\n<p>We have prepared the files with the above example in the form of code that you can run directly in Java. Download the <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2025\/01\/Vector.zip\" target=\"_blank\" rel=\"nofollow noopener\">code for Java <strong>Vector<\/strong><\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introducing Java Vector, a data structure with constructors, basic operations, advantages, disadvantages and example code.<\/p>\n","protected":false},"author":14,"featured_media":5034,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57,60],"tags":[],"class_list":["post-7913","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","category-programming"],"acf":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/7913","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/comments?post=7913"}],"version-history":[{"count":2,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/7913\/revisions"}],"predecessor-version":[{"id":42906,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/7913\/revisions\/42906"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/5034"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=7913"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=7913"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=7913"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}