/** * A fairly silly example of a class that implements the Comparable interface. * In this case, comparability from right to left. * @author gtowell * Created: March 2021 * Modified: Aug 6, 2021 */ public class CompEx implements Comparable { // The only variable private String theString; /** * Constructor * @param strng sets the internal var */ public CompEx(String strng) { theString = strng; } // getter public String getString() { return theString; } // toString public String toString() { return theString; } /** * Implements the comparable interface * Will do a case insensityve comparison of the values of the strings in each instance */ public int compareTo(CompEx o) { if (theString == null) return -1; if (o.getString() == null) return 1; // downcase both strings. String s1 = theString; String s2 = o.getString(); int l = s1.length(); if (s2.length() < l) l = s2.length(); // do a letter by letter comparison right to left -- stopping at first letter that is not the same. for (int i = (l-1); i >= 0; i--) { int d = s1.charAt(i) - s2.charAt(i); // subtract ASCII value if (d != 0) return d; } // strings are identical to length of shorter string. // Now just handle different length problem if (s1.length() == s2.length()) return 0; if (s1.length() > s2.length()) return 1; return -1; } public static void main(String[] args) { String[] a = { "a", "ab", "abc", "bac"}; String[] b = { "a", "ab", "bac", "dbc"}; for (int i = 0; i < a.length; i++) { CompEx is1 = new CompEx(a[i]); CompEx is2 = new CompEx(b[i]); System.out.println(is1 + " " + is2 + " " + is1.compareTo(is2)); System.out.println("StringComp: " + is1 + " " + is2 + " " + is1.getString().compareTo(is2.getString())); } // this line does not work because compareTo only defined for same class // System.out.println(new CompEx("AA").compareTo("BB")); } }