Skip to content

Instantly share code, notes, and snippets.

@fikovnik
Created October 29, 2012 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fikovnik/3972711 to your computer and use it in GitHub Desktop.
Save fikovnik/3972711 to your computer and use it in GitHub Desktop.
package tp3;
public abstract class Set {
public abstract boolean contains(int n);
public Set even() {
// TODO implement
return null;
}
public Set intersection(final Set that) {
return new IntersectionSet(this, that);
}
public Set union(final Set that) {
// final Set parent = this;
//
// return new Set() {
// @Override
// public boolean contains(int n) {
// return parent.contains(n) || that.contains(n);
// }
// };
return new UnionSet(this, that);
}
}
package tp3;
public class IntersectionSet extends Set {
private final Set s1;
private final Set s2;
public IntersectionSet(Set s1, Set s2) {
super();
this.s1 = s1;
this.s2 = s2;
}
@Override
public boolean contains(int n) {
return s1.contains(n) && s2.contains(n);
}
}
package tp3;
public class UnionSet extends Set {
private final Set s1;
private final Set s2;
public UnionSet(Set s1, Set s2) {
super();
this.s1 = s1;
this.s2 = s2;
}
@Override
public boolean contains(int n) {
return s1.contains(n) || s2.contains(n);
}
}
package tp3;
import static org.junit.Assert.*;
import org.junit.Test;
public class SetTest {
@Test
public void test() {
Set s1 = new SingletonSet(1);
assertTrue(s1.contains(1));
assertFalse(s1.contains(0));
Set s2 = new SingletonSet(2);
Set s12 = s1.union(s2);
assertTrue(s12.contains(1));
assertTrue(s12.contains(2));
}
}
package tp3;
class SingletonSet extends Set {
private int number;
public SingletonSet(int number) {
this.number = number;
}
public boolean contains(int n) {
return n == number;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment