use Appendable rather than StringBuffer for toJava()
[sbp.git] / src / edu / berkeley / sbp / util / DiscreteTopology.java
1 // Copyright 2006-2007 all rights reserved; see LICENSE file for BSD-style license
2
3 package edu.berkeley.sbp.util;
4 import java.io.*;
5 import java.util.*;
6 import java.lang.reflect.*;
7 import java.lang.ref.*;
8 import edu.berkeley.sbp.util.*;
9 import edu.berkeley.sbp.*;
10
11 /** implementation of <tt>Topology</tt> for any class via equals()/hashCode() */
12 public class DiscreteTopology<V> implements Topology<V> {
13
14     private static final DiscreteTopology empty = new DiscreteTopology();
15     
16     HashSet<V> hs = new HashSet<V>();
17
18     public DiscreteTopology()              { }
19     public DiscreteTopology(V v)           { hs.add(v); }
20     DiscreteTopology(HashSet<V> hs)        { this.hs.addAll(hs); }
21
22     public Topology<V> empty()             { return (Topology<V>)empty; }
23
24     public HashSet<V> hs() {
25         HashSet<V> ret = new HashSet<V>();
26         ret.addAll(hs);
27         return ret;
28     }
29         
30     public boolean          contains(V v)              { return hs.contains(v); }
31
32     public Topology<V> unwrap() { return this; }
33     public Topology<V> complement()                    { throw new Error(); }
34     public Topology<V> intersect(Topology<V> t)        { return new DiscreteTopology(hs().retainAll(((DiscreteTopology<V>)t.unwrap()).hs)); }
35     public Topology<V> minus(Topology<V> t)            { return new DiscreteTopology(hs().removeAll(((DiscreteTopology<V>)t.unwrap()).hs)); }
36     public Topology<V> union(Topology<V> t)            { return new DiscreteTopology(hs().addAll(((DiscreteTopology<V>)t.unwrap()).hs)); }
37     public boolean          disjoint(Topology<V> t)    { return ((DiscreteTopology)intersect(t).unwrap()).size()==0; }
38     public boolean          containsAll(Topology<V> t) { return hs.containsAll(((DiscreteTopology<V>)t.unwrap()).hs); }
39
40     public int     hashCode()                          { return hs.hashCode(); }
41     public boolean equals(Object o)                    { return o!=null && o instanceof DiscreteTopology && ((DiscreteTopology<V>)o).hs.equals(hs); }
42     public int size() { return hs.size(); }
43 }