對Java中String類的忽略大小寫比較器(CaseInsensitiveComparator)的compare方法的一點疑問
阿新 • • 發佈:2019-02-04
最近我在看jdk原始碼,無意中看到String類的忽略大小寫比較器的原始碼,其原始碼如下。
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; } /** Replaces the de-serialized object. */ private Object readResolve() { return CASE_INSENSITIVE_ORDER; } }
該程式碼中間首先將c1和c2先轉換成大寫字母進行比較,如果不相等然後再轉換成小寫字母進行比較,我當時認為轉換成小寫字母比較是多餘的,因為轉換成大寫字母都不相等,那麼轉換成小寫字母肯定也是不相等的,就發給了幾個朋友,與朋友進行探討。
最後在String類的public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)方法的原始碼中發現了一段非常有用的註釋,內容如下:
// Unfortunately, conversion to uppercase does not work properly // for the Georgian alphabet, which has strange rules about case // conversion. So we need to make one last check before exiting. if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) { continue; }
原來Java為了針對Georgian(喬治亞)字母表奇怪的大小寫轉換規則而專門又增加了一步判斷,就是轉換成小寫再比較一次,Java的國際化真的做的好,又增長了知識。
歡迎留言共同學習進步!