01: package JSci.maths;
02:
03: import java.util.Collections;
04: import java.util.Set;
05: import java.util.HashSet;
06:
07: /**
08: * A set containing a finite number of elements.
09: * This class provides a bridge between <code>java.util.Set</code>
10: * and <code>JSci.maths.MathSet</code>.
11: * @version 1.0
12: * @author Mark Hale
13: */
14: public final class FiniteSet extends Object implements MathSet {
15: private final Set elements;
16:
17: /**
18: * Constructs a finite set.
19: * @param set a set of elements
20: */
21: public FiniteSet(Set set) {
22: elements = set;
23: }
24:
25: /**
26: * Compares two sets for equality.
27: */
28: public boolean equals(Object s) {
29: return (s != null) && (s instanceof FiniteSet)
30: && elements.equals(((FiniteSet) s).elements);
31: }
32:
33: public int hashCode() {
34: return elements.hashCode();
35: }
36:
37: /**
38: * Returns a string representing this set.
39: */
40: public String toString() {
41: return elements.toString();
42: }
43:
44: /**
45: * Returns the elements of this set.
46: */
47: public Set getElements() {
48: return Collections.unmodifiableSet(elements);
49: }
50:
51: /**
52: * Returns the cardinality.
53: */
54: public int cardinality() {
55: return elements.size();
56: }
57:
58: /**
59: * Performs the union of this set with another.
60: * @param set a set.
61: * @return the union of the two sets.
62: */
63: public MathSet union(MathSet set) {
64: Set union = new HashSet(elements);
65: union.addAll(((FiniteSet) set).elements);
66: return new FiniteSet(union);
67: }
68:
69: /**
70: * Performs the intersection of this set with another.
71: * @param set a set.
72: * @return the intersection of the two sets.
73: */
74: public MathSet intersect(MathSet set) {
75: Set intersection = new HashSet(elements);
76: intersection.retainAll(((FiniteSet) set).elements);
77: return new FiniteSet(intersection);
78: }
79: }
|