4 // this class has static methods that implement useful,
5 // non-trivially algorithms to prevent code duplication
8 public class UtilAlgorithms {
10 // This method merge hashtable b into a, where the
11 // tables both have HashSets as the values. If both
12 // tables have a common key, the new value is the
13 // union of the sets the key mapped to in each one.
14 // Note: the reason it must be a HashSet instead of
15 // a Set is that we want to clone sets of table b, so
16 // only a is modified. Set does not provide clone().
17 static public void mergeHashtablesWithHashSetValues(Hashtable a,
19 Iterator itr = b.entrySet().iterator();
20 while( itr.hasNext() ) {
21 Map.Entry me = (Map.Entry)itr.next();
22 Object key = (Object) me.getKey();
23 HashSet s1 = (HashSet) me.getValue();
24 HashSet s2 = (HashSet) a.get(key);
27 a.put(key, s1.clone() );
35 // This method makes hashtable a the intersection of
36 // itself and hashtable b, where the new key set is the
37 // intersection. The values are sets, so if a key is
38 // common its new value should be the intersection of
39 // the existing values in a and b. If a new value is
40 // the empty set, then also remove that key.
41 static public void intersectHashtablesWithSetValues(Hashtable a,
43 Set keysToRemove = new HashSet();
45 Iterator mapItr = a.entrySet().iterator();
46 while( mapItr.hasNext() ) {
47 Map.Entry me = (Map.Entry)mapItr.next();
48 Object akey = (Object) me.getKey();
49 Set avals = (Set) me.getValue();
50 Set bvals = (Set) b.get(akey);
53 // if b doesn't have the key, mark it for
54 // safe removal after we traverse the map
55 keysToRemove.add(akey);
58 // otherwise we have the key, but pare
59 // down the value set, if needed, and if
60 // nothing is left, remove the key, too
61 avals.retainAll(bvals);
62 if( avals.isEmpty() ) {
63 keysToRemove.add(akey);
68 // then safely remove keys
69 Iterator keyItr = keysToRemove.iterator();
70 while( keyItr.hasNext() ) {
71 Object key = keyItr.next();