package demo; import java.util.ArrayList; /** * Class LooselyComparableString wraps a String and ignores case and * length when making comparisons for sort order or equality. * @author David Morris */ public class LooselyComparableString implements Comparable { String comparableString = null; /** * Method LooselyComparableString. * @param comparableString */ public LooselyComparableString(String comparableString) { this.comparableString = comparableString; } /** * @see java.lang.Object#toString() */ public String toString() { return this.comparableString; } /** * @see java.util.Comparator#compare(Object, Object) */ public int compare(Object obj1, Object obj2) { return obj1.toString().trim().compareToIgnoreCase(obj2.toString().trim()); } /** * @see java.lang.Object#equals(Object) */ public boolean equals(Object object) { // Return false if object is null otherwise do comparison test return (object == null ? false : this.compare(this.comparableString, object) == 0); } /** * @see java.lang.Object#hashCode() */ public int hashCode() { return this.comparableString.trim().toLowerCase().hashCode(); } /** * @see java.lang.Comparable#compareTo(Object) */ public int compareTo(Object object) { return compare(this, object); } /** * Method main. * @param args */ public static void main(String[] args) { LooselyComparableString unpaddedLCS = new LooselyComparableString("String"); LooselyComparableString paddedLCS = new LooselyComparableString("string "); LooselyComparableString paddedNull = null; if (unpaddedLCS.equals(paddedLCS)) { System.out.println("The loosely comparable strings are equal."); } else { System.out.println("The loosely comparable strings are not equal."); } switch (unpaddedLCS.compare("String", "String2 ")) { case 0: System.out.println("The loosely comparable strings are equal."); break; case -1: System.out.println("The first string is less than the second string."); break; case 1: System.out.println("The first string is greater than the second string."); break; } if (unpaddedLCS.equals(paddedNull)) { System.out.println("The loosely comparable string is equal to null string."); } else { System.out.println("The loosely comparable string is not equal to a null string."); } ArrayList al = new ArrayList(); al.add(unpaddedLCS); System.out.println("String \"" + unpaddedLCS + "\" added to ArrayList."); if (al.contains(paddedLCS)) { System.out.println("The ArrayList contains the string \"" + paddedLCS + "\"."); } else { System.out.println("The ArrayList doesn't contain the string \"" + paddedLCS + "\"."); } System.out.println(paddedLCS.hashCode()); System.out.println(unpaddedLCS.hashCode()); } }