// An extension of strings that is comparable. // (c) 1996 duane a. bailey package structure; public class ComparableString implements Comparable { protected String val; public ComparableString(String s) // pre: s is non-null // post: construct a ComparableString whose initial value is s. { Assert.pre(s != null, "Initial string is non-null"); val = s; } public boolean lessThan(Comparable other) // pre: other is non-null // post: returns true if this string is less than the other // string, lexically { Assert.pre(other != null,"Comparison value is non-null."); Assert.pre(other instanceof ComparableString, "lessThan expects a ComparableString"); ComparableString otherString = (ComparableString)other; return val.compareTo(otherString.value()) < 0; } public boolean equals(Object other) // pre: other is non-null // post: returns true if this string is same as other // string, lexically { Assert.pre(other != null,"Comparison value is non-null."); Assert.pre(other instanceof ComparableString, "equals expects a ComparableString"); ComparableString otherString = (ComparableString)other; return val.compareTo(otherString.value()) == 0; } public int hashCode() // pre: returns hash code associated with string. { return val.hashCode(); } public String value() // post: returns the underlying value of the string. { return val; } public String toString() // post: returns string representation { return val; } }