Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Think back to your knowledge of mathematical Set operations. The difference of t

ID: 643301 • Letter: T

Question

Think back to your knowledge of mathematical Set operations. The difference of two Sets A and B is everything that is in Set A that is NOT also in Set B. (This is also known as the complement of B in A). For example, if Set A contained {'A','C','D'} and Set B contained {'A','B','C'} then the difference of A and B (written as A - B) would contain {''D'}. Write a static method named difference that takes two Sets of Integers as parameters A and B and returns a new Set of Integers that contains A - B. The original Sets A and B should be the same after the method is finished as they were when the method started.

Explanation / Answer

package chegg;

import java.util.HashSet;
import java.util.Set;

public class Sett {
   public static void main(String args[])
   {
   HashSet<Integer> A=new HashSet<Integer>();
   HashSet<Integer> B=new HashSet<Integer>();
   A.add(1);
   A.add(2);
   A.add(3);
   B.add(1);
   B.add(2);
   B.add(4);
   difference(A,B); // Here we will get the set difference
   }
   public static HashSet difference(HashSet<Integer> A,HashSet<Integer> B)
   {
       HashSet<Integer> X=new HashSet<Integer>();
      
       for (Integer s : A)
           X.add(s);
      
       for (Integer h : B) //remove the elements which are in second set
               X.remove(h);
      
       System.out.println("First Set A is:--");
       for (Integer a : A) {
            System.out.println(a);
       }
       System.out.println("Second Set B is:--");
       for (Integer a : B) {
            System.out.println(a);
       }
       System.out.println("Difference is A-B:--");
       for (Integer a : X) {
            System.out.println(a);
       }
       return X;
   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote