Sunday 27 April 2014

TreeSet : equals : 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 TreeSetEqual{
 public static void main(String args[]){
  Set<Integer> treeSet = new HashSet<> ();
  Set<Integer> treeSet1 = new TreeSet<> ();
  Set<Integer> treeSet2 = new TreeSet<> ();
  
  /* Add Elements to the sets */
  treeSet.add(10);
  treeSet.add(20);
  treeSet.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 treeSet are");
  System.out.println(treeSet);
  
  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 treeSet and treeSet1 are equal " + treeSet.equals(treeSet1));
  System.out.println("\nIs treeSet and treeSet2 are equal " + treeSet.equals(treeSet2));
  
 }
}

Output
Elements in treeSet are
[20, 10, 30]

Elements in treeSet1 are
[10, 20, 30]

Elements in treeSet2 are
[0, 10, 20]

Is treeSet and treeSet1 are equal true

Is treeSet and treeSet2 are equal false


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment