package pt.ist.fenixframework.pstm; import java.util.Iterator; import java.util.NoSuchElementException; public class FunctionalSet { public static final FunctionalSet EMPTY = new FunctionalSet(); private int size = 0; private E element = null; private FunctionalSet next = null; private FunctionalSet() { } public synchronized int size() { return size; } public E get(int index) { if (index > size) { throw new NoSuchElementException(); } else { FunctionalSet iter = this; while (index-- > 0) { iter = iter.next; } return iter.element; } } public FunctionalSet addUnique(E obj) { FunctionalSet newSet = new FunctionalSet(); newSet.element = obj; newSet.next = this; newSet.size = this.size() + 1; return newSet; } public FunctionalSet add(E obj) { if (this.contains(obj)) { return this; } else { return addUnique(obj); } } public FunctionalSet remove(E obj) { if (! this.contains(obj)) { return this; } else { return removeExisting(obj); } } private FunctionalSet removeExisting(E obj) { FunctionalSet result = null; FunctionalSet prev = null; FunctionalSet iter = this; while (! ((obj == iter.element) || ((obj != null) && obj.equals(iter.element)))) { FunctionalSet newEntry = new FunctionalSet(); newEntry.element = iter.element; newEntry.size = iter.size() - 1; if (result == null) { result = newEntry; } else { prev.next = newEntry; } prev = newEntry; iter = iter.next; } if (result == null) { result = iter.next; } else { prev.next = iter.next; } return result; } public boolean contains(E obj) { FunctionalSet iter = this; if (obj == null) { while (iter.size() != 0) { if (iter.element == null) { return true; } iter = iter.next; } } else { while (iter.size() != 0) { if (obj.equals(iter.element)) { return true; } iter = iter.next; } } return false; } public Iterator iterator() { return new FunctionalSetIterator(this); } private static class FunctionalSetIterator implements Iterator { private FunctionalSet current; FunctionalSetIterator(FunctionalSet funcSet) { this.current = funcSet; } public boolean hasNext() { return current.size() > 0; } public E next() { if (current.size() == 0) { throw new NoSuchElementException(); } else { E res = current.element; current = current.next; return res; } } public void remove() { throw new UnsupportedOperationException(); } } }