Vector in java with examples

Java Vector

The Vector class is an implementation of the List interface that allows us to create resizable-arrays similar to the ArrayList class.

Java Vector vs. ArrayList

In Java, both ArrayList and Vector implements the List interface and provides the same functionalities. However, there exist some differences between them.

The Vector class synchronizes each individual operation. This means whenever we want to perform some operation on vectors, the Vector class automatically applies a lock to that operation.

It is because when one thread is accessing a vector, and at the same time another thread tries to access it, an exception called ConcurrentModificationException is generated. Hence, this continuous use of lock for each operation makes vectors less efficient.

However, in array lists, methods are not synchronized. Instead, it uses the Collections.synchronizedList() method that synchronizes the list as a whole.

Note: It is recommended to use ArrayList in place of Vector because vectors less efficient.

Creating a Vector

Here is how we can create vectors in Java.

Vector vector = new Vector<>(); 

Here, Type indicates the type of a linked list. For example,

// create Integer type linked list Vector vector= new Vector<>(); // create String type linked list Vector vector= new Vector<>(); 

Methods of Vector

The Vector class also provides the resizable-array implementations of the List interface (similar to the ArrayList class). Some of the Vector methods are:

Add Elements to Vector

  • add(element) — adds an element to vectors
  • add(index, element) — adds an element to the specified position
  • addAll(vector) — adds all elements of a vector to another vector
import java.util.Vector; class Main < public static void main(String[] args) < Vectormammals= new Vector<>(); // Using the add() method mammals.add("Dog"); mammals.add("Horse"); // Using index number mammals.add(2, "Cat"); System.out.println("Vector: " + mammals); // Using addAll() Vector animals = new Vector<>(); animals.add("Crocodile"); animals.addAll(mammals); System.out.println("New Vector: " + animals); > > 
Vector: [Dog, Horse, Cat] New Vector: [Crocodile, Dog, Horse, Cat] 

Access Vector Elements

  • get(index) — returns an element specified by the index
  • iterator() — returns an iterator object to sequentially access vector elements
import java.util.Iterator; import java.util.Vector; class Main < public static void main(String[] args) < Vectoranimals= new Vector<>(); animals.add("Dog"); animals.add("Horse"); animals.add("Cat"); // Using get() String element = animals.get(2); System.out.println("Element at index 2: " + element); // Using iterator() Iterator iterate = animals.iterator(); System.out.print("Vector: "); while(iterate.hasNext()) < System.out.print(iterate.next()); System.out.print(", "); >> > 
Element at index 2: Cat Vector: Dog, Horse, Cat, 

Remove Vector Elements

  • remove(index) — removes an element from specified position
  • removeAll() — removes all the elements
  • clear() — removes all elements. It is more efficient than removeAll()
import java.util.Vector; class Main < public static void main(String[] args) < Vectoranimals= new Vector<>(); animals.add("Dog"); animals.add("Horse"); animals.add("Cat"); System.out.println("Initial Vector: " + animals); // Using remove() String element = animals.remove(1); System.out.println("Removed Element: " + element); System.out.println("New Vector: " + animals); // Using clear() animals.clear(); System.out.println("Vector after clear(): " + animals); > > 
Initial Vector: [Dog, Horse, Cat] Removed Element: Horse New Vector: [Dog, Cat] Vector after clear(): [] 

Others Vector Methods

Methods Descriptions
set() changes an element of the vector
size() returns the size of the vector
toArray() converts the vector into an array
toString() converts the vector into a String
contains() searches the vector for specified element and returns a boolean result

Table of Contents

Источник

Vector in Java Tutorial with Examples

Java Vector tutorial with examples will help you understand how to use Vector class in an easy way. The Vector in Java is an implementation of the List interface that grows automatically as we add elements to it.

The Vector class is contained in the java.util package so we have to import the java.util package using the import statement to use the Vector class in the code.

The Vector class was a part of Java 1.0, but in Java 2, the Vector class was rewritten to implement the List interface and thus it became the part of the Java Collection Framework.

Java Vector Tutorial

Unlike the ArrayList class in Java, the Vector is synchronized but it comes with a cost. If the application does not need thread safety, it is recommended to use the ArrayList instead of the Vector class to get better performance.

Like the ArrayList, the Vector class is also a dynamic array of objects. It maintains an internal array to store its elements and the size of this array is increased or decreased automatically as needed. The size of this internal array is called the capacity of the Vector.

The size of the internal array is increased automatically by a certain number when the vector size becomes greater than the internal array size. This certain number is called the capacity increment of the Vector.

The Vector elements can be accessed using the index just like an array. The index of the elements starts from 0 and ends at the size of the vector – 1 index.

How to create new objects of the Java Vector class?

The Vector class in Java provides several constructors using which we can create new objects of it. The default constructor creates a new and empty vector object.

Источник

Vector in Java

Vector in Java

A vector in java is one of the legacy classes available in java and is available in java. util package. Vector internally contains a dynamical array that can increase or decrease itself as per requirement. Components inside a vector can be accessed using an integer-valued index. In comparison to the array list, the vector is thread-safe and contains legacy methods that are not available in the collection framework. It is to be noted that since the vector is a legacy class, it is immutable and thread-safe in nature.

Web development, programming languages, Software testing & others

// create vector instance Vector vectorobj=new Vector(); //call required method vectorobj.methodName();

Here is the declaration of vector class in java.

public class Vector extends AbstractListimplements List,RandomAccess,Cloneable,Serializable

How to Create Vector in Java?

Vector is a part of the Legacy framework. The following are the main constructors of the Vector Class.

  • Vector(): This creates an empty vector with a default capacity of 10 elements.
  • Vector(Collection c): This creates a vector containing all specified collection elements in the order the collection’s iterator returns them.
  • Vector(int initialCapacity): This creates an empty vector with a specified initial capacity.
  • Vector(int initialCapacity, int incrementCapacity): This creates an empty vector with specified initial capacity and capacity increment.

If incremental capacity in the vector is specified along with initial capacity, the vector will expand itself according to incremental capacity in each element addition cycle, but if increment capacity is not specified, then the vector’s capacity gets doubled in each addition cycle.

Examples to Implement Vector in Java

Here are some of the examples of vector in java as follows:

Example #1

Let us see a basic example of the vector class in java as given below.

import java.util.*; public class VectorDemo < public static void main(String args[])< // Creating a vector instance which is not type safe and can contain any type of element Vector vector= new Vector(); vector.add(1); vector.add(5); vector.add("Edubca"); vector.add("Java"); vector.add("Training"); vector.add(4); System.out.println("Vector has the following elements " + vector); // Creating a vector instance which is type safe // This can contain only String elements. If any other type of element is added, it will result in compile //time error. VectortypeSafeVector= new Vector(); typeSafeVector.add("Edubca"); typeSafeVector.add("Java"); typeSafeVector.add("Training"); System.out.println("Vector has the following elements " + typeSafeVector); > >

Vector in Java eg1

The above code shows the creation of a java vector class, and it adds a method. Also, we have seen how to create a type-safe vector. The following output will be produced:

Example #2

In this example, we will see some more methods of Vector class like add at the specified position and get the element at a specified index in vector.

import java.util.*; public class VectorDemo < public static void main(String args[])< Vectorvector= new Vector(); vector.add("Edubca"); vector.add("Java"); vector.add("Training"); System.out.println("Original Vector has the following elements " + vector); vector.add(1, "Provides"); // adding element at specified position System.out.println("Modified Vector has the following elements " + vector); String elementAtFirst= vector.get(0); //get element at first position in vector System.out.println("Element at first position in vector is " + elementAtFirst); String elementAtThird = vector.get(2); //get element at third position in vector System.out.println("Element at Third position in vector is " + elementAtThird ); > >

In the above example, we have seen how to create a Vector class and usage of its methods. The above code will display the following as output.

Vector in Java eg2

Example #3

In this example, we will see how to create a vector from an existing collection and contain the vector class method.

import java.util.*; public class VectorDemo < public static void main(String args[])< HashSet set =new HashSet(); set.add("first"); set.add("second"); set.add("third"); set.add("fourth"); Vector vector= new Vector(set); System.out.println("Vector created from Hashset is " + vector); System.out.println(vector.contains("third")); System.out.println(vector.contains("fifth")); >>

Vector in Java eg3

Example #4

In this example we will see the use of remove(), isEmpty() and clear() methods in Vector.

import java.util.*; public class VectorDemo < public static void main(String args[])< HashSet set =new HashSet(); set.add("This"); set.add("is"); set.add("Vector"); set.add("Class"); set.add("Demo"); set.add("In"); set.add("Java"); Vector vector= new Vector(set); System.out.println("Vector created from Hashset is " + vector); vector.remove(1); vector.remove(3); System.out.println("Vector after removal of Elements " + vector); System.out.println("Is Vector Empty : " + vector.isEmpty()); vector.clear(); // Clear All Elements of Vector System.out.println("Vector After Calling Clear method : " + vector); System.out.println("Is Vector Empty : " + vector.isEmpty()); >>

Here is the output produced after running the above code.

output produced after running the code

Example #5

In this example, we will see how to iterate elements of a vector using an iterator.

import java.util.*; public class VectorDemo < public static void main(String args[])< Vectorvector= new Vector(); vector.add("Welcome"); vector.add("To"); vector.add("Edubca"); vector.add("Java"); vector.add("Training"); Iterator it=vector.iterator(); System.out.println("Vector elements as traversed by iterator are : "); while(it.hasNext()) < System.out.println(it.next()); >> >

The above code will produce the following output.

Output

Conclusion

From the above discussion, we have a clear understanding of what is Vector in java, how it’s created, and the different methods available in vector class. Also, the vector is thread-safe, and therefore it can be used in a multithreading environment.

This is a guide to Vector in Java. Here we discuss the basic concept, creating a vector in java, and examples and code implementation. You can also go through our suggested articles to learn more –

500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access

1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access

1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access

3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access

All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access

Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access

Источник

Читайте также:  Проверить содержит ли строка символ java
Оцените статью