Created
November 8, 2013 05:05
-
-
Save haoch/7366519 to your computer and use it in GitHub Desktop.
Why need compare both UpperCase and LowerCase in comparing case insensitively?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static class CaseInsensitiveComparator | |
implements Comparator<String>, java.io.Serializable { | |
// use serialVersionUID from JDK 1.2.2 for interoperability | |
private static final long serialVersionUID = 8575799808933029326L; | |
public int compare(String s1, String s2) { | |
int n1 = s1.length(); | |
int n2 = s2.length(); | |
int min = Math.min(n1, n2); | |
for (int i = 0; i < min; i++) { | |
char c1 = s1.charAt(i); | |
char c2 = s2.charAt(i); | |
if (c1 != c2) { | |
c1 = Character.toUpperCase(c1); | |
c2 = Character.toUpperCase(c2); | |
if (c1 != c2) { | |
c1 = Character.toLowerCase(c1); | |
c2 = Character.toLowerCase(c2); | |
if (c1 != c2) { | |
// No overflow because of numeric promotion | |
return c1 - c2; | |
} | |
} | |
} | |
} | |
return n1 - n2; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment