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

HashSet <String> returnSet = new HashSet (); //an empty HashSet is created. retu

ID: 3834801 • Letter: H

Question

HashSet <String>  returnSet = new HashSet (); //an empty HashSet is created.

    returnSet.addAll    (set1);

  returnSet.retainAll (set2);

   ---------------------------------------------------------------------------------------

what would be the most likely results of the above segment of three statements assuming that set1 and set2 are also a Hashset each?

returnSet would contain the union of set1 and set2.

returnSet would contain the intersection of set1 and set2.

returnSet would contain the difference of set1 and set2, set1--set2.

returnSet would contain the difference of set2 and set1, set2--set1.

a.

returnSet would contain the union of set1 and set2.

b.

returnSet would contain the intersection of set1 and set2.

c.

returnSet would contain the difference of set1 and set2, set1--set2.

d.

returnSet would contain the difference of set2 and set1, set2--set1.

Explanation / Answer

Answer is b. Result set would contain the intersection of set1 and set2.

addAll method will add all the elements in the collection set1 to the return set.

retainAll method will retain only the elements present in the set2. That would be the intersection of the set1 and set2. Given an example java program :

import java.io.*;
import java.util.*;


public class Sample1 {

public static void main(String[] args) {
HashSet<String> set = new HashSet();
HashSet<String> set1 = new HashSet();
set1.add("a");
set1.add("b");
set1.add("c");
HashSet<String> set2 = new HashSet();
set2.add("d");
set2.add("b");
set2.add("f");
set.addAll(set1);
set.retainAll(set2);
System.out.println(set);
}
}

OUTPUT :

b

output is b since it is intersection of both the sets.

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