// We define our own order relation on strings. Strings are ordered by length. // import java.util.*; public class MyString implements Comparable { public String contents; public MyString(String s) { contents = s; } public int getLength() { return contents.length(); } public String toString() { return contents; } // Redefine equality to be compatible --- not necessary but a good idea. // Note that you have to redefine the equals method that takes an Object // argument, since that's what existing methods that call equals will be // looking for. So you have to do a cast. // public boolean equals(Object o) { if (!(o instanceof MyString)) return false; MyString s = (MyString) o; // cast Object to String return getLength() == s.getLength(); } public int compareTo(MyString s) { if (getLength() < s.getLength()) return -1; else if (getLength() > s.getLength()) return 1; else return 0; } public int hashCode() { return (new Integer(getLength()).hashCode()); } public static void main(String[] args) { MyString how = new MyString("How"); MyString much = new MyString("much"); MyString wood = new MyString("wood"); MyString could = new MyString("could"); System.out.println("much.equals(wood) => " + ( much.equals(wood) ? "true" : "false")); System.out.println("how.compareTo(could) => " + how.compareTo(could)); List l = new ArrayList(); l.add(wood); l.add(how); l.add(could); l.add(much); Collections.sort(l); System.out.println(l); HashMap h = new HashMap(); h.put(much, 15); System.out.println(h.get(wood)); } }