1 package no.uio.ifi.refaktor.prefix;
3 import java.util.HashSet;
4 import java.util.Iterator;
5 import java.util.LinkedList;
9 * A set for collecting prefixes (see {@link Prefix}}).
11 * It is based on a regular Set<Prefix>, but is used to
12 * add some more functionality to the basic set, like
13 * incrementing a counter in a prefix each time an equal
14 * prefix is registered with the set. In addition
15 * it can produce the set that is this set, minus the
16 * prefixes from another set that are enclosed by the
17 * prefixes in this set.
19 public class PrefixSet implements Iterable<Prefix> {
21 private final Set<Prefix> prefixes = new HashSet<Prefix>();
26 private PrefixSet(PrefixSet initialElements) {
27 prefixes.addAll(initialElements.prefixes);
30 public boolean add(Prefix prefix) {
31 return prefixes.add(prefix);
34 private void remove(Prefix prefix) {
35 prefixes.remove(prefix);
38 public boolean contains(Prefix prefix) {
39 return prefixes.contains(prefix);
43 public Iterator<Prefix> iterator() {
44 return prefixes.iterator();
47 public boolean isEmpty() {
48 return prefixes.isEmpty();
51 public LinkedList<Prefix> toList() {
52 return new LinkedList<Prefix>(prefixes);
55 public void register(Prefix prefix) {
56 if (contains(prefix)) {
57 incrementCountFor(prefix);
63 private void incrementCountFor(Prefix prefix) {
64 get(prefix).incrementCount();
67 public Prefix get(Prefix prefix) {
68 for (Prefix p: this) {
75 public void registerAllSubPrefixesOf(Prefix prefix) {
76 for (Prefix p: prefix.getSubPrefixes())
81 public String toString() {
83 for (Prefix p: this) {
84 str += p.toString() + " (" + p.getCount() + ")\n";
90 * Creates a set of prefixes that are the prefixes of this set,
91 * minus the prefixes that are enclosing the prefixes of the
92 * other set. A prefix is enclosing another if the other prefix
93 * is a sub-prefix of the first prefix.
95 * @param other The set of prefixes that are to be checked against this one.
96 * @return The set of prefixes that are not enclosing the ones in the other set.
98 public PrefixSet minusEnclosedPrefixesFrom(PrefixSet other) {
99 PrefixSet prefixSet = shallowCopy();
100 removeEnclosingPrefixesFromPrefixSet(prefixSet, other);
104 private PrefixSet shallowCopy() {
105 return new PrefixSet(this);
108 private void removeEnclosingPrefixesFromPrefixSet(PrefixSet prefixSet, PrefixSet other) {
109 for (Prefix p: other) {
110 for (Prefix prefix: this) {
111 if (prefix.hasSubPrefix(p))
112 prefixSet.remove(prefix);
117 public void clear() {