package containers; import java.util.Enumeration; import ordered.IOrdered; /** * A ordered container implemented using arrays. * * Version 1. * * @author Alan L. Cox * @since 03/19/01 */ public class OAVers2Container implements IOrderedContainer { private int _firstEmptyPair = 0; private OrderedKeyValuePair[] _pairs = new OrderedKeyValuePair[1]; /** * Returns either (1) the index of the key if it is stored * in the array or (2) the index of the next smaller key * if it is NOT stored in the array. (If there is NOT * a smaller key in the array, returns -1.) */ private int findIndex(IOrdered key) { int lo = -1; int hi = _firstEmptyPair; while (lo + 1 != hi) { int mid = lo + (key - a[lo + 1])*(hi - lo)/(a[hi - 1] - a[lo + 1]); switch (_pairs[mid].getKey().compare(key)) { case IOrdered.EQUAL: return mid; case IOrdered.GREATER: hi = mid; break; case IOrdered.LESS: lo = mid; break; } } return lo; } /** * If there is an object associated with key * then this object is returned else null is returned. */ public Object find(IOrdered key) { int index = findIndex(key); if ((index >= 0) && (_pairs[index].getKey().compare(key) == IOrdered.EQUAL)) return _pairs[index].getValue(); return null; } /** * Afterwards, find(key) returns null, and if there is * an object associated with key then this object is * returned else null is returned. */ public Object remove(IOrdered key) { int index = findIndex(key); if ((index >= 0) && (_pairs[index].getKey().compare(key) == IOrdered.EQUAL)) { Object value = _pairs[index].getValue(); int i = index; for (_firstEmptyPair--; i < _firstEmptyPair; i++) _pairs[i] = _pairs[i + 1]; _pairs[i] = null; return value; } return null; } /** * (key, value) is stored in this container with no * duplication and such that find(key) returns value. */ public void insert(IOrdered key, Object value) { int index = findIndex(key); if ((index >= 0) && (_pairs[index].getKey().compare(key) == IOrdered.EQUAL)) { _pairs[index] = new OrderedKeyValuePair(key, value); return; } if (_firstEmptyPair == _pairs.length) { OrderedKeyValuePair[] newPairs = new OrderedKeyValuePair[2*_pairs.length]; for (int i = 0; i < _pairs.length; i++) newPairs[i] = _pairs[i]; _pairs = newPairs; } int i = _firstEmptyPair; for (index++; i > index; i--) _pairs[i] = _pairs[i - 1]; _pairs[i] = new OrderedKeyValuePair(key, value); _firstEmptyPair++; } /** * Returns an Enumeration of the container. The objects returned * by nextElement() are KeyValuePair's. * * @return an Enumeration of the container. */ public Enumeration enumeration() { return new Enumeration() { private int _nextPair = 0; public boolean hasMoreElements() { return _nextPair < _firstEmptyPair; } public Object nextElement() { OrderedKeyValuePair pair = _pairs[_nextPair]; _nextPair++; return pair; } }; } }