SHARE
TWEET

set operations

a guest Jan 21st, 2020 57 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.*;
  2.  
  3. class MySet extends HashSet<String> {
  4.   private static final long serialVersionUID = 1L;
  5.  
  6.   public MySet() {
  7.     super();
  8.   }
  9.  
  10.   /**
  11.    * @return the union of the elements of this and that
  12.    */
  13.   public MySet union(MySet that) {
  14.     MySet result = new MySet();
  15.     result.addAll(this);
  16.     if (that == null || that.size() < 1) {
  17.       return result;
  18.     }
  19.     result.addAll(that);
  20.     return result;
  21.   }
  22.  
  23.   /**
  24.    * @return the intersection of the elements of this and that
  25.    */
  26.   public MySet intersection(MySet that) {
  27.     MySet result = new MySet();
  28.     if (that == null || that.size() < 1) {
  29.       return result;
  30.     }
  31.     for (String s : this) {
  32.       if (that.contains(s)) {
  33.         result.add(s);
  34.       }
  35.     }
  36.     return result;
  37.   }
  38.  
  39.   /**
  40.    * @return the difference of the elements of this and that
  41.    */
  42.   public MySet difference(MySet that) {
  43.     MySet result = new MySet();
  44.     if (that == null || that.size() < 1) {
  45.       result.addAll(this);
  46.       return result;
  47.     }
  48.     for(String s : this) {
  49.       if (!that.contains(s)) {
  50.         result.add(s);
  51.       }
  52.     }
  53.     return result;
  54.   }
  55.  
  56.   /**
  57.    * @return the exclusive or (XOR) of the elements of this and that
  58.    */
  59.   public MySet exclusiveOr(MySet that) {
  60.     MySet result = new MySet();
  61.     if (that == null || that.size() < 1) {
  62.       result.addAll(this);
  63.       return result;
  64.     }
  65.     MySet intersection = this.intersection(that);
  66.     MySet union = this.union(that);
  67.     for (String s : union) {
  68.       if(!intersection.contains(s)) {
  69.         result.add(s);
  70.       }
  71.     }
  72.     return result;
  73.   }
  74.  
  75.   /**
  76.    * @return a String representation of a MySet object
  77.    */
  78.   public String toString() {
  79.     String res = "<MySet{";
  80.     for (String s : this) {
  81.       res += s + ",";
  82.     }
  83.     res = res.substring(0, res.length() - 1);
  84.     res += "}>";
  85.     return res;
  86.   }
  87. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top