package java.util; public class TreeSet implements Iterable { private PersistentSet> set; private int size; public TreeSet(final Comparator comparator) { set = new PersistentSet(new Comparator>() { public int compare(Cell a, Cell b) { return comparator.compare(a.value, b.value); } }); size = 0; } public Iterator iterator() { return new MyIterator(set.first()); } public boolean add(T value) { PersistentSet.Path> p = set.find(new Cell(value, null)); if (p.fresh()) { set = p.add(); ++size; return true; } return false; } // Used by hashMaps for replacement public void addAndReplace(T value) { PersistentSet.Path> p = set.find(new Cell(value, null)); if (p.fresh()) { set = p.add(); ++size; } else { set = p.replaceWith(new Cell(value, null)); } } public boolean remove(T value) { PersistentSet.Path> p = set.find(new Cell(value, null)); if (p.fresh()) { return false; } else { --size; if (p.value().next != null) { set = p.replaceWith(p.value().next); } else { set = p.remove(); } return true; } } public int size() { return size; } private class MyIterator implements java.util.Iterator { private PersistentSet.Path> path; private PersistentSet.Path> nextPath; private Cell cell; private Cell prevCell; private Cell prevPrevCell; private boolean canRemove = false; private MyIterator(PersistentSet.Path> path) { this.path = path; if (path != null) { cell = path.value(); nextPath = path.successor(); } } private MyIterator(MyIterator start) { path = start.path; nextPath = start.nextPath; cell = start.cell; prevCell = start.prevCell; prevPrevCell = start.prevPrevCell; canRemove = start.canRemove; } public boolean hasNext() { return cell != null || nextPath != null; } public T next() { if (cell == null) { path = nextPath; nextPath = path.successor(); cell = path.value(); } prevPrevCell = prevCell; prevCell = cell; cell = cell.next; canRemove = true; return prevCell.value; } public void remove() { if (! canRemove) throw new IllegalStateException(); --size; if (prevPrevCell != null && prevPrevCell.next == prevCell) { // cell to remove is not the first in the list. prevPrevCell.next = prevCell.next; prevCell = prevPrevCell; } else if (prevCell.next == cell && cell != null) { // cell to remove is the first in the list, but not the last. set = (PersistentSet) path.replaceWith(cell); prevCell = null; } else { // cell is alone in the list. set = (PersistentSet) path.remove(); path = path.successor(); if (path != null) { prevCell = null; cell = path.value(); path = (PersistentSet.Path) set.find((Cell) cell); } } canRemove = false; } } }