package no.uio.ifi.refaktor.extractors; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; /** * A set for collecting prefixes (see {@link Prefix}}). * * It is based on a regular Set, but is used to * add some more functionality to the basic set, like * incrementing a counter in a prefix each time an equal * prefix is registered with the set. In addition * it can produce the set that is this set, minus the * prefixes from another set that are enclosed by the * prefixes in this set. */ public class PrefixSet implements Iterable { private final Set prefixes = new HashSet(); public PrefixSet(PrefixSet initialElements) { prefixes.addAll(initialElements.prefixes); } public PrefixSet() { } public boolean add(Prefix prefix) { return prefixes.add(prefix); } private void remove(Prefix prefix) { prefixes.remove(prefix); } public boolean contains(Prefix prefix) { return prefixes.contains(prefix); } @Override public Iterator iterator() { return prefixes.iterator(); } public boolean isEmpty() { return prefixes.isEmpty(); } public LinkedList toList() { return new LinkedList(prefixes); } public void register(Prefix prefix) { if (contains(prefix)) { incrementCountFor(prefix); } else { add(prefix); } } private void incrementCountFor(Prefix prefix) { get(prefix).incrementCount(); } public Prefix get(Prefix prefix) { for (Prefix p: this) { if (p.equals(prefix)) return p; } return null; } public void registerAllSubPrefixesOf(Prefix prefix) { for (Prefix p: prefix.getSubPrefixes()) register(p); } @Override public String toString() { String str = ""; for (Prefix p: this) { str += p.toString() + " (" + p.getCount() + ")\n"; } return str; } public Map toMap() { Map map = new HashMap(); for (Prefix prefix: this) map.put(prefix.getPrefixString(), prefix); return map; } private PrefixSet shallowCopy() { return new PrefixSet(this); } /** * Creates a set of prefixes that are the prefixes of this set, * minus the prefixes that are enclosing the prefixes of the * other set. * * @param other The set of prefixes that are to be checked against this one. * @return The set of prefixes that are not enclosing the ones in the subtract set. */ public PrefixSet minusEnclosedPrefixesFrom(PrefixSet other) { PrefixSet prefixSet = shallowCopy(); for (Prefix subtrahend: other) { for (Prefix prefix: this) { if (prefix.encloses(subtrahend)) prefixSet.remove(prefix); } } return prefixSet; } }