package plp.collection; import java.util.*; public class OrderedSet { private final Map table = new HashMap(); private final AVL avl = new AVL(); private void checkAbsent(Object o) throws InvalidObjectException { if (table.containsKey(o)) { throw new InvalidObjectException(o); } } public void insertAt(int rank, Object o) throws InvalidObjectException, InvalidRankException { checkAbsent(o); table.put(o, avl.insertAt(o, rank)); } private AVLPosition position(Object o) throws InvalidObjectException { AVLPosition pos = (AVLPosition) table.get(o); if (pos == null) { throw new InvalidObjectException(o); } return pos; } public void insertAfter(Object predecessor, Object o) throws InvalidObjectException { checkAbsent(o); table.put(o, position(predecessor).insertAfter(o)); } public void insertBefore(Object successor, Object o) throws InvalidObjectException { checkAbsent(o); table.put(o, position(successor).insertBefore(o)); } public void remove(Object o) throws InvalidObjectException { position(o).remove(); table.remove(o); } public void remove(int rank) throws InvalidRankException { Object o = get(rank); try { remove(o); } catch (InvalidObjectException e) { throw new Error(); } } public Object get(int rank) throws InvalidRankException { return avl.data(rank); } public int getRank(Object o) throws InvalidObjectException { return position(o).rank(); } public int size() { return table.size(); } public Object [] toArray() { return avl.dfs(); } public String toString() { String s = ""; try { for (int i = 0; i < size(); ++ i) { s += "(" + i + ":" + get(i) + ") "; } } catch (InvalidRankException e) { throw new Error(); } return s; } }