Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Vector in Java | Vector Methods Example

 Vector in Java


Vector class in Java was introduced in JDK 1.0. It is present in Java.util package. It is a dynamically resizable array (growable array) which means it can grow or shrink as required.

Vector class is similar to ArrayList class with two main differences.
1. Vector is synchronized. It is used for thread safety.
2. It contains many legacy methods that are not a part of collections framework.

Hierarchy Diagram of Vector class in Java


Vector class implements list interface and extends AbstractList. It also implements three marker interface such as serializable, cloneable, and random access interface. The current hierarchy diagram of a Vector class is shown in the below figure.

Features of Vector class


1. The underlying Data structure for vector class 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 in the Java vector class.

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 the vector class are synchronized. That means it is a thread-safe. Two threads cannot access vector object at the same time. Only one thread can access can enter to access 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 form.

 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 in Java


There are four ways to create an object of vector class in Java. They are as follows:

Vector vec = new Vector();
It creates a vector list with default initial capacity of 10. Inside the vector class, data is stored as an array of objects according to its initial size that you specify in the constructor. Since default initial capacity is 10. So, we can store only 10 elements. 
 
When 11th element is inserted into vector, the capacity of vector will be exceeded. In this case. a new internal array will be automatically created that is equal to size of old array plus capacity increment specified in the constructor. 
If you do not specify an initial capacity and capacity increment, each time vector will be resized due to exceeding its capacity. A new internal array will create which copies all the original elements of old array into the new array by using System.arraycopy() method.
Creating a new array and copying elements will take more time. Therefore, it is important to assign the value of 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 that will be 20.
After resizing, it copies all original elements of old array into new array using System.arraycopy() method and then it will insert 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. Look at the below figure.

Similarly, If we remove an element at a specific position, the same process is performed by vector and elements will be shifted one position up.

But vector is not a good choice in inserting and removal of elements because it will take more time to copy elements into new array and will get slower as the size of the vector grows.

Vector vec = new Vector(int initialCapacity);
For example:
    Vector vec = new Vector(3); // It will create an empty vector with initial capacity of 3.
Vector v = new Vector(int initialCapacity, capacityIncrement);

For example:
    Vector v = new Vector(3, 5);

Vector v = new Vector(Colletion c);

For example,
    Vector v = new Vector(list1); // list1 is elements of the collection.

Code to create Generic Vector class object

We can also create a vector object in generic form like this:

Vector vec = new Vector(); // T is the type of generic.
For example:
    Vector vec = new Vector(); // It will store only string type element.
     Vector v = new Vector(3,6);

Vector Methods in Java


The Vector class provides many different methods to create, access, and modify data structure. They are as follows:
1. boolean add(Object o): It is used to add the specified element to the end of given vector. It will return true if the specified element is added successfully into 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 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.

Java Vector Class Example Programs


Let’s take an example program based on above vector methods.
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. 
   Vector v = new Vector(); 
// Check the size of 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 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 collection of elements into vector. 
    v.addAll(al); 
// Now check size and capacity of the vector. 
   int vsize = v.size(); 
   System.out.println("Size: " +vsize); 
   int vcapacity = v.capacity(); 
   System.out.println("Vcapacity: " +vcapacity); 

// Adding 11th element to check 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 11th element into 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 v = new Vector(); 
// Adding elements to 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 of data type 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 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 vec = new Vector(); 
// 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 element oxygen with helium. 
   vec.setElementAt("Helium", 1); 
   vec.set(2, "Lithium"); 
  System.out.println("Elements after replacing: " +vec); 
// Check 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 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) 
{ 
 Vector v = new Vector(); 
 for(int i = 0; i 
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?


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 and Vector in Java


 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
Hope that this tutorial has covered almost all important topics under vector in Java with example programs. I hope that you will have understood and enjoyed programs based on vector methods.
Thanks for reading!!!

Next ⇒ Java Vector Example Programs⇐ PrevNext ⇒

The post Vector in Java | Vector Methods Example appeared first on Scientech Easy.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

Vector in Java | Vector Methods Example

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×