Tuesday 6 May 2014

Vector : equals : Checks for Equality

public synchronized boolean equals(Object o)
Returns true if and only if the specified Object is a List and they contain the same elements in the same order.

import java.util.*;

class VectorEquals{
 public static void main(String args[]){
  Vector<Integer> myVector1;
  Vector<Integer> myVector2;
  Vector<Integer> myVector3;
  
  myVector1 = new Vector<> ();
  myVector2 = new Vector<> ();
  myVector3 = new Vector<> ();
  
  /* Add Elements to myVector1 and myVector2*/
  for(int i=1; i<6; i++){
   myVector1.add(i); 
   myVector2.add(i); 
  }
  
  /* Add Elements to myVector3 */
  for(int i=5; i>=1; i--){
   myVector3.add(i);
  }
  
  System.out.println("Elements in myVector1 are");
  System.out.println(myVector1);
  System.out.println("Elements in myVector2 are");
  System.out.println(myVector2);
  System.out.println("Elements in myVector3 are");
  System.out.println(myVector3);
  
  System.out.print("Is myVector1 and myVector2 are Equal ");
  System.out.println(myVector1.equals(myVector2));
  
  System.out.print("Is myVector1 and myVector3 are Equal ");
  System.out.println(myVector1.equals(myVector3));
 }
}

Output
Elements in myVector1 are
[1, 2, 3, 4, 5]
Elements in myVector2 are
[1, 2, 3, 4, 5]
Elements in myVector3 are
[5, 4, 3, 2, 1]
Is myVector1 and myVector2 are Equal true
Is myVector1 and myVector3 are Equal false

As you observe the output even both myVector1 and myVector3 has same elements, but the equals method returns false. Since the order of elements in myVector1 and myVector3 is different.

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment