Write a Java program to compare two Vector collections


The code you provided demonstrates how to compare two vectors using the equals method in Java. Here's a breakdown of what the code does:

  • Three Vector<String> objects, vec_list1, vec_list2, and vec_list3, are created.
  • Elements "Apple", "Banana", "Cherry", and "Mango" are added to vec_list1 using the add method.
  • The same elements are added to vec_list2.
  • Elements "Orange", "Mango", and "Apple" are added to vec_list3.
  • The current contents of vec_list1, vec_list2, and vec_list3 are printed using System.out.println.
  • The equals method is used to compare vec_list1 with vec_list2. If the two vectors have the same elements in the same order, the message "Vectors list1 and list2 have Same Elements." is printed. Otherwise, the message "Vectors list1 and list2 does Dot Same Elements." is printed.
  • Similarly, the equals method is used to compare vec_list1 with vec_list3, and the appropriate message is printed based on the result of the comparison.

As you can see, vec_list1 and vec_list2 have the same elements in the same order, so the first comparison returns true. On the other hand, vec_list1 and vec_list3 have different elements or elements in a different order, so the second comparison returns false.

Source Code

import java.util.*;
public class Compare_TwoVector
{
	public static void main(String[] args)
	{
		Vector < String > vec_list1 = new Vector < String > ();
		Vector < String > vec_list2 = new Vector < String > ();
		Vector < String > vec_list3 = new Vector < String > ();
 
		vec_list1.add("Apple");
		vec_list1.add("Banana");
		vec_list1.add("Cherry");
		vec_list1.add("Mango");
 
		vec_list2.add("Apple");
		vec_list2.add("Banana");
		vec_list2.add("Cherry");
		vec_list2.add("Mango");
 
		vec_list3.add("Orange");
		vec_list3.add("Mango");
		vec_list3.add("Apple");
 
		System.out.println("Vector List 1 : " + vec_list1);
		System.out.println("Vector List 2 : " + vec_list2);
		System.out.println("Vector List 3 : " + vec_list3);
 
		if (vec_list1.equals(vec_list2))
		{
			System.out.println("Vectors list1 and list2 have Same Elements.");
		}
		else
		{
			System.out.println("Vectors list1 and list2 does Dot Same Elements.");
		}
 
		if (vec_list1.equals(vec_list3))
		{
			System.out.println("Vectors list1 and list3 have Same Elements.");
		}
		else
		{
			System.out.println("Vectors list1 and list3 does Dot Same Elements.");
		}
	}
}

Output

Vector List 1 : [Apple, Banana, Cherry, Mango]
Vector List 2 : [Apple, Banana, Cherry, Mango]
Vector List 3 : [Orange, Mango, Apple]
Vectors list1 and list2 have Same Elements.
Vectors list1 and list3 does Dot Same Elements.

Example Programs