Scientech Easy Vector in Java | Vector Methods & Example Programs | Scientech Easy

Wednesday, November 21, 2018

Vector in Java | Vector Methods & Example Programs

When you know the size of your collection and all the elements in the collection are of the same type, arrays are good to use but what will you do when you don't know the size of the array in advance? In this case, Vector is very useful when you don't know the size of the array in advance. In this tutorial, we will learn Vector in Java with example and programs in a simple way. 

Vector in Java


The Vector class was introduced in JDK 1.0. It is present in Java.util package.
Vector is a dynamically resizable array or growable array that means it can grow or shrink as required. It is similar to ArrayList with two main difference.
1. Vector is synchronized. It is used for thread safety.
2. It contains many legacy methods which are not a part of a collections framework.

Hierarchy Diagram of Vector class


Vector class implements the list interface and extends AbstractList. It also implements three marker interface such as Serializable, Cloneable, and RandomAccess interface. The current hierarchy diagram of a Vector class is shown in below picture.
Vector in java, What is vector in java, Vector in java examples programs, Vector methods, vector constructor, vector vs arraylist in java
Hierarchy diagram of the Vector class


Features of Vector class in Java


1. The underlying Data structure for the vector is the resizable array or growable array.
2. Duplicate elements are allowed in the vector class.
3. It preserves the insertion order in Java.
4. Null elements are allowed.
5. Heterogeneous elements are allowed in the vector class. Therefore, it can hold elements of any type and any number. 
6. Most of the methods present in Vector are synchronized. i.e It is a thread-safe that means two thread cannot access the vector object at the same time. Only one thread can access can enter to access the vector object at a time.
7. Vector class is preferred where we are developing a multi-threaded application but it gives poor performance because it is thread-safety.
8. Vector is rarely used in a non-multithreaded environment due to synchronized that gives you poor performance in searching, adding, delete, and update of its element.
9. It can be iterated by a simple for loop, Iterator, ListIterator, and Enumeration.
10. Vector is the best choice if the frequent operation is retrieval (getting).

Java Vector Class Constructors


Vector class provides four types of constructors to create, access, and modify the data structure. They are listed below in Table.
SN Constructor Description
1. vector() It creates an empty vector with default initial capacity of 10.
2. vector(int initialCapacity) It creates an empty vector with specified initial capacity.
3. vector(int initialCapacity, int capacityIncrement) It creates an empty vector with specified initial capacity and capacity increment.
4. vector(Collection c) It creates a vector that contains the element of collection c.


Ways to create Vector class object


There are four ways to create the object of vector class in Java. They are:
1. Vector vec=new Vector(); // It creates vector with default initial capacity of 10. Inside the vector class, the data is stored as an array of objects according to its initial size that you specify in the constructor. Since the default, initial capacity is 10. So we can store only 10 elements. 

When the 11th element is inserted into the vector, the capacity of the vector will be exceeded. In this case. a new internal array will be automatically created that is equal to the size of the old array plus capacity increment specified in the constructor. 
If you do not specify an initial capacity and capacity increment, each time the vector will be resized due to exceeding its capacity and a new internal array will create which copies all the original elements of the old array into the new array by using System.arraycopy() method. Creating a new array and copying the elements will take more time. Therefore, It is important to assign the value of the initial capacity and capacity increment for minimizing the number of resizing operations without wasting too much memory and time. 
In this object creation, we did not specify any capacity increment in the constructor, so its size will be double by default i.e 20.  After resizing, it copies all original elements of the old array into the new array using the System.arraycopy() method and then it will insert the 11th element.

When we add an element at a specific position, the vector uses a System.arraycopy() method to move the element from that specific position to the one position down into the array. See the below picture.
Inserting an elements into a vector at an index

Similarly, If we remove an element at a specific position, the same process is performed by the vector and the elements will be shifted one position up but the vector is not a good choice in inserting and removal of the elements because it will take more time to copy the elements into the new array and will get slower as the size of the vector grows. 

2. Vector vec=new Vector(int initialCapacity); 
For example,
    Vector vec=new Vector(3); // It will create an empty vector with initial capacity of 3.
3. Vector v=new Vector(int initialCapacity, capacityIncrement); 
For example,
    Vector v=new Vector(3, 5); 
4. Vector v=new Vector(Colletion c); 
For example,
    Vector v=new Vector(list1); // list1 is the elements of the collection.

Code to create Generic Vector
We can also create a vector object in generic form like this:
1. Vector<T> vec=new Vector<T>(); // T is the type of generic.
For example,
    Vector<String> vec=new Vector<String>(); // It will store only string type element.
     Vector<Integer> v=new Vector<Integer>(3,6);

Vector Methods in Java


The Vector class provides many different methods to create, access, and modify the data structure. They are given below.
1. boolean add(Object o): It is used to add the specified element to the end of the given vector. It will return true if the specified element is added successfully into the vector otherwise, it will return false.
For example
     v.add("John"); 
2. void add(int index, Object o): This method is used to insert a specified element at a specific position into the vector. It returns nothing.
For example
    v.add(4, "John"); //  It adds the element 'John' at position 4 in the vector.
3. boolean addAll(Collection c): It adds a collection of elements to a vector. It returns true if the collection of elements is successfully added in the vector otherwise, false. If the collection is null, it will throw NullPointerException
For example
    v.addAll(list2);
4. boolean addElement(Object o): It adds an element to the end of a vector. It increases the vector size by one. 
For example
    v.addElement("Cat"); 
5. int capacity(): It is used to get the current capacity of a vector or length of array present in the vector. Its return type is Integer value. This method does not take any parameter.
For example
    v.capacity();
6. int size(): It returns the number of elements in a vector. 

Note: The difference between the size() and capacity() is that size() is the number of elements that are currently held whereas capacity() is the number of elements that can maximum hold. 
Program source code 1:
    package vectorTest; import java.util.ArrayList; import java.util.Vector; public class VectorTest1 { public static void main(String[] args) { // Create an empty vector object with an initial capacity of 5 and type String. Vector v=new Vector(); // Check the size of the vector before adding elements. int size=v.size(); System.out.println("Size of vector before adding elements: " +size); // Adding elements to a vector using reference variable v. v.add("Red"); v.add("Green"); v.add("Yellow"); v.add("Pink"); v.add("White"); System.out.println("Vector elements: " +v); // Check the size and capacity. int vectorsize=v.size(); System.out.println("Size: " +vectorsize); int capacity=v.capacity(); System.out.println("Default capacity: " +capacity); // Adding elements using addElement() method. v.addElement(null); v.addElement(20); v.add(5, 15); int newsize=v.size(); System.out.println("New size after adding elements: " +newsize); int newcapacity=v.capacity(); System.out.println("New capacity after adding elements: " +newcapacity); System.out.println("Elements order after addition: " +v); // Create an ArrayList with an initial capacity of 10. ArrayList al=new ArrayList(); // Adding elements using reference variable al. al.add("Brown"); al.add("Black"); // Call addAll() method to add the collection of elements into the vector. v.addAll(al); // Now check the size and capacity of the vector. int vsize=v.size(); System.out.println("Size: " +vsize); int vcapacity=v.capacity(); System.out.println("Vcapacity: " +vcapacity); // Add the 11th element to check the size and capacity. v.add(10); System.out.println("Elements: " +v); int vecsize=v.size(); System.out.println("Size after adding 11th element: " +vecsize); int cap=v.capacity(); System.out.println("Capacity after adding 11th element: " +cap); } }
    Output: Size of vector before adding elements: 0 Vector elements: [Red, Green, Yellow, Pink, White] Size: 5 Default capacity: 10 New size after adding elements: 8 New capacity after adding elements: 10 Elements order after addition: [Red, Green, Yellow, Pink, White, 15, null, 20] Size: 10 Vcapacity: 10 Elements: [Red, Green, Yellow, Pink, White, 15, null, 20, Brown, Black, 10] Size after adding 11th element: 11 Capacity after adding 11th element: 20
In this example program, you can see that when we added the 11th element in the vector, its capacity become double. 
7. void clear(): It clears or removes all elements from a vector.
For example
             v.clear();
8. Object clone(): It creates a clone of a vector.
For example
             v.clone();
9. boolean contains(Object o): It will return true if the vector contains the specified element.
For example
           v.contains("A");  
10. void copyInto(Object[ ] anArray): It copies the elements of a vector into a specified array.
For example
      v.copyInto(arr); // arr is the reference variable of specified array object.
11. Object elementAt(int index): It returns an element at a specific position.
For example
      v.elementAt(2);
12. Object firstElement(): It returns the element stored at index position 0.
For example
      v.firstElement();
Program source code 2: 
    package vectorTest; import java.util.Vector; public class VectorTest2 { public static void main(String[] args) { // Create an empty generic vector with an initial capacity of 10. Vector<String> v=new Vector<String>(); // Adding elements to a vector. v.add("A"); v.add("B"); v.add("C"); v.add("D"); v.add("E"); System.out.println("Elements: " +v); // Call firstElement() method to get the first element using reference variable v. // Since the return type of firstElement method is String. Therefore, we will store it using variable firstElement with datatype String. String firstElement=v.firstElement(); System.out.println("First Element: " +firstElement); String lastElement=v.lastElement(); System.out.println("Last Element: " +lastElement); String element=v.elementAt(3); System.out.println("Element at position 3: " +element); boolean checkElement=v.contains("F"); // Return type of contains method is boolean. System.out.println("Element F: " +checkElement); // Create an array object with an initial capacity of 5. String[] arr=new String[5]; // Copy the collection of elements into an array str. v.copyInto(arr); System.out.println("Elements in an array arr"); for(String str:arr){ System.out.println(str); } // Call clone() method to create a clone of a vector Object obj=v.clone(); // Return type of clone method is an Object. System.out.println("Clone of v: " +obj); } }
    Output: Elements: [A, B, C, D, E] First Element: A Last Element: E Element at position 3: D Element F: false Elements in an array arr A B C D E Clone of v: [A, B, C, D, E]
13. Object get(int index): This method is used to get an element at a specific position in the vector.
For example
      v.get(2); // It will return an element from position 2.
14. int hashCode(): This method returns hash code value for a vector.
For example
      v.hashCode();
15. int indexOf(Object o): It returns the index of the first occurrence of a specified element in the vector. It returns -1 if the vector does not contain the element.
For example
      v.indexOf("C");
16. int lastIndexOf(Object o): It returns the index of the last occurrence of the specified element in the vector. It returns -1 if the vector does not contain the element.
17. void insertElementAt(Object o, int index): It inserts an element into the vector.
For example
      v.insertElementAt("C", 4);
18. boolean remove(Object o): It removes or clears the first occurrence of a specific element in the vector. 
19. boolean removeAll(Collection c): It removes a collection of elements from the vector.
20. void removeAllElements(): It deletes all elements from the vector and set the size of the vector to zero.
21. boolean removeElement(Object o): It clears the first occurrence of a specific element from a vector.
For example
      v.removeElement("Ball");
22. void removeElementAt(int index): It remove an element at specific position from the vector.
Program source code 3: 
    package vectorTest; import java.util.Vector; public class VectorTest3 { public static void main(String[] args) { Vector v=new Vector(); v.add("Bat"); v.add("Ball"); v.add("Wicket"); v.add("Stump"); v.add("Pitch"); v.add(25); v.add(null); System.out.println("Elements: " +v); Object getElement=v.get(5); // Return type of get method is an Object. System.out.println("Element at position 5: " +getElement); Integer hashcode=v.hashCode(); // Return type is an Integer. System.out.println("HashCode value: " +hashcode); Integer indexOfElement=v.indexOf(null); System.out.println("Index of element null: " +indexOfElement); v.insertElementAt("Gloves", 6); v.removeElement(25); v.remove(6); System.out.println("Elements after removing: " +v); } }
    Output: Elements: [Bat, Ball, Wicket, Stump, Pitch, 25, null] Element at position 5: 25 HashCode value: 461290222 Index of element null: 6 Elements after removing: [Bat, Ball, Wicket, Stump, Pitch, Gloves]
23. boolean isEmpty(): It is used to check if the vector is empty. If the vector is empty, it will return true otherwise, false.
24. void removeRange(int fromIndex, toIndex): It is used to remove a range of elements from a vector. This method does not return any value. It accepts two parameters.
fromIndex: Starting index from where you have to remove.
toIndex: the last index as far as you have to remove all elements.
For example
         v.removeRange(3, 6); 
24. void set(): It is used to change the element at a specified position with the specified element in the vector.
25. void setElementAt(Object o, int index): It is used to change an element at a specific position with a specified element within the vector.
For example
       v.setElement("B", 4); 
26. void setSize(int newSize): It is used to change the size of an internal vector buffer.
27. boolean equals(Object o): It is used to check the equality with another object or element. It returns true if the element is matched.
For example
      v.equals(v1); 
Program source code 4: 
    package vectorTest; import java.util.Vector; public class VectorTest4 { public static void main(String[] args) { Vector<String> vec=new Vector<String>(); // Check vector is empty or not. boolean check=vec.isEmpty(); System.out.println("Vector is empty: " +check); vec.add("Hydrogen"); vec.add("Oxygen"); vec.add("Boron"); vec.add("Beryllium"); vec.add("Boron"); System.out.println("Elements: " +vec); boolean check1=vec.isEmpty(); System.out.println("Vector is empty: " +check1); // Replace the element oxygen with helium. vec.setElementAt("Helium", 1); vec.set(2, "Lithium"); System.out.println("Elements after replacing: " +vec); // Check the size of the vector. int size=vec.size(); System.out.println("Size of the vector: " +size); // Setting new size of the vector. vec.setSize(8); System.out.println("Size of the vector after setting: " +vec.size()); // Check the capacity of the vector. int capacity=vec.capacity(); System.out.println("Capacity of the vector: " +capacity); // Check the equality of element carbon. boolean equality=vec.equals("Carbon"); System.out.println("Is Carbon present: " +equality); } }
    Output: Vector is empty: true Elements: [Hydrogen, Oxygen, Boron, Beryllium, Boron] Vector is empty: false Elements after replacing: [Hydrogen, Helium, Lithium, Beryllium, Boron] Size of the vector: 5 Size of the vector after setting: 8 Capacity of the vector: 10 Is Carbon present: false
28. void ensureCapacity(int minCapacity): This method is used to increase the capacity of the vector at a certain size.
For example
      v.ensureCapacity(15);
29. void trimToSize(): It is used to trim the capacity of the vector to the vector's actual size.
30. String toString(): It converts vector contents into a string. It returns a string representation of the vector.
For example
        v.toString();
31. object[ ] toArray(): It returns the elements of a vector as an array. 
Program source code 5:
    package vectorTest; import java.util.Vector; public class VectorTest5 { public static void main(String[] args) { // Create a generic vector object with an initial capacity of 10. Vector<Integer> v=new Vector<Integer>(); for(int i=0; i<=10; i++){ if(i%2==0){ v.add(i); System.out.println(i); } } int size=v.size(); System.out.println("Size of the vector: " +size); int capacity=v.capacity(); System.out.println("Capacity of the vector: " +capacity); // Ensuring capacity. v.ensureCapacity(25); // Checking capacity. System.out.println("Minimum capacity: " +v.capacity()); // Trim the capacity of the vector to the actual size. v.trimToSize(); System.out.println("Minimum capacity after trimming: " +v.capacity()); // String representation of the vector. String str=v.toString(); System.out.println("String equivalent of the vector: " +str); // Get the elements of the vector as an array form. v.toArray(); System.out.println(v); } }
    Output: 0 2 4 6 8 10 Size of the vector: 6 Capacity of the vector: 10 Minimum capacity: 25 Minimum capacity after trimming: 6 String equivalent of the vector: [0, 2, 4, 6, 8, 10] [0, 2, 4, 6, 8, 10]

When to Use Vector in Java

The vector can be used when
➤ We want to store duplicate elements.
➤ We want to store null elements.
➤ We are developing a multi-threaded application but it can reduce the performance of the application because it is "thread-safety".
➤ Vector is more preferred when the retrieval of elements is more as compared to insertion and removals of elements. 
➤ Vector is a good choice if you want to access the data in the list rapidly and a poor choice if the data in the list is modified frequently. 

Difference between ArrayList & Vector

SN ArrayList Vector
1. ArrayList is not synchronized. Vector is synchronized.
2. Since ArrayList is not synchronized. Hence, its operation is faster as compared to vector. Vector is slower than ArrayList.
3. ArrayList was introduced in JDK 2.0. Vector was introduced in JDK 1.0.
4. ArrayList is created with an initial capacity of 10. Its size is increased by 50%. Vector is created with an initial capacity of 10 but its size is increased by 100%.
5. In the ArrayList, Enumeration is fail-fast. Any modification in ArrayList during the iteration using Enumeration will throw ConcurrentModificatioException. Enumeration is fail-safe in the vector. Any modification during the iteration using Enumeration will not throw any exception.
Final words
We hope that this article will help you to learn Vector in Java and its various method with example programs. All programs are very important to clear the concepts. So practice them.   




Popular