Tuesday, April 2, 2013

Java: Set Intersection

/*
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.
*/

  1. import java.util.HashSet;

  2. import java.util.Iterator;

  3. import java.util.NoSuchElementException;

  4. import java.util.Set;


  5. public class SetIntersection {

  6. /**

  7. * @param args

  8. */


  9. private static Set<Object> s1;

  10. private static Set<Object> s2;

  11. public static Set<Object> getIntersection(Set<Object> a, Set<Object> b) {

  12. /*

  13. Please implement this method to

  14. return a Set equal to the intersection of the parameter Sets

  15. The method should not chage the content of the parameters.

  16. */


  17. s1 =a;

  18. s2 = b;

  19. Object ob;

  20. Set<Object> s3 = new HashSet<Object>();



  21. Iterator<Object> it1 = s1.iterator();

  22. Iterator<Object> it2 = s2.iterator();


  23. System.out.println("Set 1");

  24. while(it1.hasNext())

  25. {

  26. System.out.println(it1.next());

  27. }

  28. System.out.println("Set 2");

  29. while(it2.hasNext())

  30. {

  31. System.out.println(it2.next());

  32. }


  33. it1 = s1.iterator();

  34. while(it1.hasNext())

  35. {

  36. System.out.println("hi");

  37. try

  38. {

  39. ob = it1.next();

  40. //System.out.println(ob);

  41. if(s2.contains(ob))

  42. {

  43. // System.out.println("contain element is "+ob);

  44. s3.add(ob);

  45. }

  46. }

  47. catch(ClassCastException cse)

  48. {

  49. cse.printStackTrace();

  50. }

  51. catch(NoSuchElementException ne)

  52. {

  53. ne.printStackTrace();

  54. }



  55. }


  56. return s3;

  57. }



  58. public static void main(String[] args) {

  59. // TODO Auto-generated method stub

  60. Set<Object> s1 = new HashSet<Object>();

  61. Set<Object> s2 = new HashSet<Object>();

  62. s1.add(3);

  63. s1.add(4);

  64. s1.add(5);

  65. s1.add(7);

  66. s1.add("hi");

  67. s1.add(3.4);

  68. s2.add(1);

  69. s2.add(2);

  70. s2.add(3);

  71. s2.add(7);

  72. s2.add("hi");

  73. s2.add(new Object());

  74. Set<Object> s3 = getIntersection(s1,s2);

  75. Iterator<Object> it = s3.iterator();

  76. System.out.println("Set 3");

  77. while(it.hasNext())

  78. {

  79. System.out.println(it.next());

  80. }

  81. }

  82. }


Download Link: Click Here

0 comments: