KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > JSci > maths > FiniteSet


1 package JSci.maths;
2
3 import java.util.Collections JavaDoc;
4 import java.util.Set JavaDoc;
5 import java.util.HashSet JavaDoc;
6
7 /**
8 * A set containing a finite number of elements.
9 * 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 JavaDoc implements MathSet {
15         private final Set JavaDoc elements;
16         /**
17         * Constructs a finite set.
18         * @param set a set of elements
19         */

20         public FiniteSet(Set JavaDoc set) {
21                 elements = set;
22         }
23         /**
24         * Compares two sets for equality.
25         */

26         public boolean equals(Object JavaDoc s) {
27                 return (s != null) && (s instanceof FiniteSet) && elements.equals(((FiniteSet)s).elements);
28         }
29     public int hashCode() {
30         return elements.hashCode();
31     }
32         /**
33         * Returns a string representing this set.
34         */

35         public String JavaDoc toString() {
36                 return elements.toString();
37         }
38         /**
39         * Returns the elements of this set.
40         */

41         public Set JavaDoc getElements() {
42                 return Collections.unmodifiableSet(elements);
43         }
44         /**
45         * Returns the cardinality.
46         */

47         public int cardinality() {
48                 return elements.size();
49         }
50         /**
51         * Performs the union of this set with another.
52         * @param set a set.
53         * @return the union of the two sets.
54         */

55         public MathSet union(MathSet set) {
56                 Set JavaDoc union = new HashSet JavaDoc(elements);
57                 union.addAll(((FiniteSet)set).elements);
58                 return new FiniteSet(union);
59         }
60         /**
61         * Performs the intersection of this set with another.
62         * @param set a set.
63         * @return the intersection of the two sets.
64         */

65         public MathSet intersect(MathSet set) {
66                 Set JavaDoc intersection = new HashSet JavaDoc(elements);
67                 intersection.retainAll(((FiniteSet)set).elements);
68                 return new FiniteSet(intersection);
69         }
70 }
71
72
Popular Tags