Tuesday, September 4, 2012

Classical operations on Set

Classical operations on SET
Generally set supports union, intersection and minus operations.

The UNION of two sets is the set of elements which are in either set.
For example: let A = (1,2,3) and let B = (3,4,5). Now the UNION of A and B, written A union B = (1,2,3,4,5). There is no need to list the 3 twice.

The INTERSECTION of two sets is the set of elements which are in both sets.
For example: let A = (1,2,3) and B = (3,4,5). The INTERSECTION of A and B, written A intersection B = (3).

The MiNUS Of two sets is the set elements from A which does not exist in the B.
For example: let A = (1,2,3) and B = (3,4,5). the minus of A and B (A-B) , written A minu B = (1,2)

import java.util.HashSet;

public class SetOperations {
 public static void main(String[] args) {
 
  HashSet<Integer> setA = new HashSet<Integer>();
  HashSet<Integer> setB = new HashSet<Integer>();
 
  setA.add(1);setA.add(2);setA.add(3);
  setB.add(3);setB.add(4);setB.add(5);
 
 
  System.out.println(setA);
  System.out.println(setB);
 
  //UNION
  setA.addAll(setB);
  System.out.println(setA);
 
  /*
  //INTERSECTION
  setA.retainAll(setB);
  System.out.println(setA);
  */
 
  /*
   * //MINUS
  setA.removeAll(setB);
  System.out.println(setA);
  */
 
 
 
 }
}

No comments:

Post a Comment