Merges the two item sets belonging to the members a and b. The merged set contains at least a and b even if a or b did not have an associated item set. Returns false if the item sets of a and b are non-empty and already identical, true otherwise.
(T a, T b)
| 80 | * true otherwise. |
| 81 | */ |
| 82 | public boolean union(T a, T b) { |
| 83 | Set<T> aItems = itemSets_.get(a); |
| 84 | Set<T> bItems = itemSets_.get(b); |
| 85 | // check if the sets are already identical |
| 86 | if (aItems != null && bItems != null && aItems == bItems) return false; |
| 87 | |
| 88 | // union(x, x) is equivalent to makeSet(x) |
| 89 | if (a.equals(b) && aItems == null) { |
| 90 | makeSet(a); |
| 91 | return true; |
| 92 | } |
| 93 | |
| 94 | // create sets for a or b if not present already |
| 95 | if (aItems == null) aItems = makeSet(a); |
| 96 | if (bItems == null) bItems = makeSet(b); |
| 97 | |
| 98 | // will contain the union of aItems and bItems |
| 99 | Set<T> mergedItems = aItems; |
| 100 | // always the smaller of the two sets to be merged |
| 101 | Set<T> updateItems = bItems; |
| 102 | if (bItems.size() > aItems.size()) { |
| 103 | mergedItems = bItems; |
| 104 | updateItems = aItems; |
| 105 | } |
| 106 | for (T item: updateItems) { |
| 107 | mergedItems.add(item); |
| 108 | itemSets_.put(item, mergedItems); |
| 109 | } |
| 110 | Object removedValue = uniqueSets_.remove(updateItems); |
| 111 | Preconditions.checkState(removedValue == DUMMY_VALUE); |
| 112 | return true; |
| 113 | } |
| 114 | |
| 115 | /** |
| 116 | * Merges all the item sets corresponding to the given items. Returns true if any item |