UPDATE: Okay, marginally I understand what I was doing in the post, below, but I have no idea what problem it fixed. The description is awful. I mean, it must have done something for me, but I now have no idea what. Way to go, self.


So spaces come before letters, either case in our good friend, the American Standard Code for Information Interchange. This is a pain, because it means Java's Collections' binarySearch is going to tell us an entry for "special sauce" should come before "special", which probably isn't what we wanted. So we've got to write our own Comparator to make things pop out the right way.

Here's what I've got so far. Enjoy. Well named, I might add.
(c) 2008 Bailey
package com.rufwork.run;

import java.util.Comparator;

public class JoeComparator implements Comparator {

public int compare(Object arg0, Object arg1) {
int intReturn = 0;
String strFirst = arg0.toString();
String strSecond = arg1.toString();

int intShorter = 0;

if (strFirst.length() < strSecond.length()) {
intShorter = strFirst.length();
} else {
intShorter = strSecond.length();
}

int i = 0;

while (0 == intReturn && i<intShorter) {
int intCharForFirst = strFirst.charAt(i);
int intCharForSecond = strSecond.charAt(i);

// we want "space" to come *after* all chars
// otherwise "special sauce" comes *before*
// "special"
if (32 == intCharForFirst) {
intCharForFirst = 257;
}
if (32 == intCharForSecond) {
intCharForSecond = 257;
}

if (intCharForFirst < intCharForSecond) {
intReturn = -1;
} else if (intCharForFirst > intCharForSecond) {
intReturn = 1;
}

i++;
}

// we only know right now that the strings are the same
// to the length of the shorter string.
if (0 == intReturn) {
if (strFirst.length() < strSecond.length()) {
intReturn = -1; // strFirst comes first
} else if (strFirst.length() > strSecond.length()) {
intReturn = 1;
} // if they are the same length, stay at 0
}


if (false) { // some debugging jive
if (1==intReturn) {
System.out.println(strFirst
+ " is larger than " + strSecond);
} else if (-1==intReturn) {
System.out.println(strSecond
+ " is larger than " + strFirst);
} else if (0 ==intReturn) {
System.out.println("Same strings: "
+ strFirst + " :: " + strSecond);
} else {
System.out.println("Something wack happend: "
+ strFirst + " :: " + strSecond);
}
}

return intReturn;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

}

}

Labels: , ,