// using 0-based indexes instead of 1-based positions: +(nValues+1) for where value should have been found but wasn't private int getIndex(T value) // O(n) { assert value != null; // do not allow null values to be added int index = 0; for (; index < size(); index++) // traverse with an index-based getEntry { int compare = value.compareTo(getEntry(index)); if (compare < 0) // value should have appeared here index += size() + 1; // mark as "should have appeared here" if (compare <= 0) break; // no need to look further } return index; } // using 0-based indexes instead of 1-based positions: +(nValues+1) for where value should have been found but wasn't private int getIndex(T value) // O(n) { assert value != null; // do not allow null values to be added int index = 0; for (T dataValue: this) // traverse with an iterator { int compare = value.compareTo(dataValue); if (compare < 0) // value should have appeared here index += size() + 1; // mark as "should have appeared here" if (compare <= 0) break; // no need to look further ++index; } return index; }Instead of negative return values to indicate no-match-found as in Carrano, these methods add size+1 to the return value.
public interface MySortedList<T extends Comparable<? super T>> extends MyList<T> { public boolean remove(T value); // removes 1st instance of matching reference }public boolean add(T value) is already in "MyList", but needs to be redefined so as to not add to the end. public boolean add(int, T value) exists in "MyList", but cannot be used. Nor can public boolean replace(int, T value), because they can upset the sortedness of the data structure. So we either have to make a new interface that does not derive from "MyList", or do this:
public boolean add(int index, T value) { throw new UnsupportedOperationException(getClass().getName() + ".add(int, T) is not supported"); } public boolean replace(int index, T value) { throw new UnsupportedOperationException(getClass().getName() + ".replace(int, T) is not supported"); }
[ Home | Contact Prof. Burns ]