Please implement this method to
return a Set equal to the intersection of the parameter Sets
The method should not chage the content of the parameters.
*/
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- import java.util.Set;
- public class SetIntersection {
- /**
- * @param args
- */
- private static Set<Object> s1;
- private static Set<Object> s2;
- public static Set<Object> getIntersection(Set<Object> a, Set<Object> b) {
- /*
- Please implement this method to
- return a Set equal to the intersection of the parameter Sets
- The method should not chage the content of the parameters.
- */
- s1 =a;
- s2 = b;
- Object ob;
- Set<Object> s3 = new HashSet<Object>();
- Iterator<Object> it1 = s1.iterator();
- Iterator<Object> it2 = s2.iterator();
- System.out.println("Set 1");
- while(it1.hasNext())
- {
- System.out.println(it1.next());
- }
- System.out.println("Set 2");
- while(it2.hasNext())
- {
- System.out.println(it2.next());
- }
- it1 = s1.iterator();
- while(it1.hasNext())
- {
- System.out.println("hi");
- try
- {
- ob = it1.next();
- //System.out.println(ob);
- if(s2.contains(ob))
- {
- // System.out.println("contain element is "+ob);
- s3.add(ob);
- }
- }
- catch(ClassCastException cse)
- {
- cse.printStackTrace();
- }
- catch(NoSuchElementException ne)
- {
- ne.printStackTrace();
- }
- }
- return s3;
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Set<Object> s1 = new HashSet<Object>();
- Set<Object> s2 = new HashSet<Object>();
- s1.add(3);
- s1.add(4);
- s1.add(5);
- s1.add(7);
- s1.add("hi");
- s1.add(3.4);
- s2.add(1);
- s2.add(2);
- s2.add(3);
- s2.add(7);
- s2.add("hi");
- s2.add(new Object());
- Set<Object> s3 = getIntersection(s1,s2);
- Iterator<Object> it = s3.iterator();
- System.out.println("Set 3");
- while(it.hasNext())
- {
- System.out.println(it.next());
- }
- }
- }
Download Link: Click Here

0 comments:
Post a Comment