import java.util.Arrays; import java.util.Comparator; /** From lecture 7/2/2004: illustrating instanceof and Comparator. */ public class ScrabbleCompExample { public static void main(String[] args) { /** A string array as test data. */ String[] strings = new String[] {"SEA", "martin", "Bishop", "ding", "Joe Schmoe", "fubar"}; Arrays.sort(strings); //the strings should now be in character order (i.e. alphabetical) printStrings(strings); Comparator scomp = new ScrabbleComp(); Arrays.sort(strings, scomp); //the strings should now be in order by length, longest first printStrings(strings); } /** Print every element of an array. */ private static void printStrings(Object[] strings) { for (int s = 0; s < strings.length; s++) { System.out.println(strings[s]); } } } //end class /** A string comparator exactly as coded in class 7/2/2004. * */ class ScrabbleComp implements Comparator { /** Compare strings, considering the longer one as "better" * (coming first). This is NOT really a proper Scrabble * comparator! A real one would take into account the value * of the individual letters, etc. */ public int compare(Object ob1, Object ob2) { if (ob1 instanceof String && ob2 instanceof String) { int len1 = ((String) ob1).length(); int len2 = ((String) ob2).length(); if (len1 < len2) { return +1; } if (len2 < len1) { return -1; } return 0; } //at least one of the objects is not a String. //A questionable design choice. //An alternative might be to convert both objects to a String! //That can always be done using toString(). return 0; } }