TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Java Vector: java.util.Vector

These Java examples show the Vector type, from java.util.Vector. Vector is a resizable, thread-safe array.

Vector. A resizable array, like ArrayList, Vector stores typed elements.

We use angle brackets in its syntax. It is found in java.util.Vector.

Add, for-loop. This program shows the basic syntax for Vector. It adds two Integers to an Integer Vector. It then uses the for-loop to display those elements to the console.

Diamonds: The right side of the Vector declaration uses diamond inference syntax. The "Integer" type is inferred by the compiler.

Based on:

Java 7

Java program that uses Vector

import java.util.Vector;

public class Program {
    public static void main(String[] args) {

	// Add two values to Vector.
	Vector<Integer> v = new Vector<>();
	v.add(100);
	v.add(1000);

	// Display values.
	for (int value : v) {
	    System.out.println(value);
	}
    }
}

Output

100
1000

Get element. We access elements in a Vector with the get() method. And with a for-loop, we can call get() on all indexes. This accesses every element in the Vector.

Java program that uses get

import java.util.Vector;

public class Program {
    public static void main(String[] args) {

	Vector<Integer> v = new Vector<>();
	v.add(20);
	v.add(30);
	v.add(40);

	// ... Get element 0.
	System.out.println(v.get(0));

	// ... Loop over all indexes, calling get.
	for (int i = 0; i < v.size(); i++) {
	    int value = v.get(i);
	    System.out.println(value);
	}
    }
}

Output

20
30
40

Set element. Set() assigns an element value at an index within the vector. It returns the value of the old, replaced element. SetElementAt is an older method—its arguments are reversed.

Java program that uses set, setElementAt

import java.util.Vector;

public class Program {
    public static void main(String[] args) {

	// Create one-element Vector.
	Vector<Integer> v = new Vector<>();
	v.add(20);

	// Set index 0.
	int old = v.set(0, 30);

	// Display old and current value.
	System.out.println(old);
	System.out.println(v.get(0));

	// Set index 0 with setElementAt.
	v.setElementAt(40, 0);
	System.out.println(v.get(0));
    }
}

Output

20
30
40

AddAll, ArrayList. Here we add the contents of an ArrayList to a Vector. We add three elements to ArrayList. Then we call addAll to add them to our Vector.

Size: Finally we use the size() method on the Vector. Three elements (Strings) are stored within the collection.

Strings

Java program that adds ArrayList to Vector

import java.util.ArrayList;
import java.util.Vector;

public class Program {
    public static void main(String[] args) {

	// Create new ArrayList.
	ArrayList<String> values = new ArrayList<>();
	values.add("cat");
	values.add("dog");
	values.add("mouse");

	// Add ArrayList to Vector.
	Vector<String> v = new Vector<String>();
	v.addAll(values);

	// Display size of Vector.
	System.out.println(v.size());
    }
}

Output

3

Convert Vector to array. Suppose we have a Vector, but want an array. With the toArray method, this conversion is easily done. The empty String array is allocated and filled.

Arrays

Java program that converts Vector, array

import java.util.Vector;

public class Program {
    public static void main(String[] args) {

	// Add ArrayList to Vector.
	Vector<String> v = new Vector<>();
	v.add("one");
	v.add("two");
	v.add("three");

	// ... Convert Vector into String array.
	String[] array = {};
	String[] result = v.toArray(array);
	for (String value : result) {
	    System.out.println(value);
	}
    }
}

Output

one
two
three

Search. With contains and indexOf we search a Vector. Contains returns true if the specified element exists. IndexOf meanwhile returns the element's index (or negative one if not found).

Java program that uses contains, indexOf

import java.util.Vector;

public class Program {
    public static void main(String[] args) {

	Vector<Integer> v = new Vector<>();
	v.add(5);
	v.add(10);
	v.add(15);
	v.add(20);

	// See if 15 is present.
	if (v.contains(15)) {
	    System.out.println("Contains 15");
	}

	// Get index of value 20.
	int index = v.indexOf(20);
	System.out.println("index of 20 = " + index);
    }
}

Output

Contains 15
index of 20 = 3

Vector versus ArrayList. Vector is an older Java collection, but it has been updated over time. Unlike ArrayList, Vector is thread-safe. This causes a performance loss.

ArrayList

Benchmark. Here I benchmark an ArrayList against a Vector. The ArrayList, which is not thread-safe, is about twice as fast as Vector when adding many elements.

Thus: Replacing Vector with ArrayList will likely lead to a performance increase in programs.

Java that benchmarks ArrayList, Vector

import java.util.ArrayList;
import java.util.Vector;

public class Program {
    public static void main(String[] args) {

	long t1 = System.currentTimeMillis();

	// ... Add to ArrayList.
	ArrayList<Integer> a = new ArrayList<>();
	for (int i = 0; i < 100000; i++) {
	    a.add(i);
	}

	long t2 = System.currentTimeMillis();

	// ... Add to Vector.
	Vector<Integer> v = new Vector<>();
	for (int i = 0; i < 100000; i++) {
	    v.add(i);
	}

	long t3 = System.currentTimeMillis();

	// ... Times.
	System.out.println(t2 - t1);
	System.out.println(t3 - t2);
    }
}

Results

 5 ms, ArrayList
10 ms, Vector

Sort. We sort a Vector by passing it to the Collections.sort method, found in java.util.Collections. The Vector is sorted in-place. By default the sorting order is ascending.

Sort: Collections.sort

Stack. In the Stack collection, a LIFO (last-in-first-out) algorithm is used. Stack is based on Vector: for this reason it is deprecated.

Stack

In programs with threads, a Vector may be a better choice than ArrayList. And Vector is used in older programs that precede ArrayList. Removing Vector is often an optimization.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf