Friday, 21 March 2014

Check for Set Equality

boolean equals(Object o)
     returns true if the two sets are equal else false.

Two sets are said to be equal if they contain same elements.

import java.util.*;
class SetEqual{
 public static void main(String args[]){
  Set<Integer> hashSet1 = new HashSet<> ();
  Set<Integer> treeSet1 = new TreeSet<> ();
  Set<Integer> treeSet2 = new TreeSet<> ();
  
  /* Add Elements to the sets */
  hashSet1.add(10);
  hashSet1.add(20);
  hashSet1.add(30);
  
  treeSet1.add(30);
  treeSet1.add(20);
  treeSet1.add(10);
  
  treeSet2.add(0);
  treeSet2.add(20);
  treeSet2.add(10);
  
  System.out.println("Elements in hashSet1 are");
  System.out.println(hashSet1);
  
  System.out.println("\nElements in treeSet1 are");
  System.out.println(treeSet1);
  
  System.out.println("\nElements in treeSet2 are");
  System.out.println(treeSet2);
  
  System.out.println("\nIs hashSet1 and treeSet1 are equal " + hashSet1.equals(treeSet1));
  System.out.println("\nIs hashSet1 and treeSet2 are equal " + hashSet1.equals(treeSet2));
  
 }
}
Output

Elements in hashSet1 are
[20, 10, 30]

Elements in treeSet1 are
[10, 20, 30]

Elements in treeSet2 are
[0, 10, 20]

Is hashSet1 and treeSet1 are equal true

Is hashSet1 and treeSet2 are equal false


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment