Browse Source

fix ArrayIndexOutOfBoundsException

sunyj 8 years ago
parent
commit
2b7d24bfd8

+ 12 - 2
mall-search/src/main/java/com/uas/search/sort/StringFieldComparatorSource.java

@@ -83,12 +83,16 @@ public class StringFieldComparatorSource extends FieldComparatorSource {
             }
 
             /**
-             * 比较字母顺序,优先级:字母 > 其他字符(优先级视为相等) > 数字
+             * 比较字母顺序,优先级:字母 > 数字 > 其他字符(优先级视为相等)
              */
             private int compareCharacter(String str1, String str2) {
                 char[] array1 = str1.toLowerCase().toCharArray();
                 char[] array2 = str2.toLowerCase().toCharArray();
-                for (int i = 0; i < array1.length; i++) {
+                int length1 = array1.length;
+                int length2 = array2.length;
+                // 取最小的长度
+                int length = length1 < length2 ? length1 : length2;
+                for (int i = 0; i < length; i++) {
                     char c1 = array1[i];
                     char c2 = array2[i];
                     // 字母 > 数字 > 其他字符(优先级视为相等)
@@ -120,6 +124,12 @@ public class StringFieldComparatorSource extends FieldComparatorSource {
                         }
                     }
                 }
+                // 如果字母比较完毕,顺序仍然一致,则比较哪一方还剩有字母未比较
+                if (length1 < length2) {
+                    return AHEAD;
+                } else if (length1 > length2) {
+                    return BEHIND;
+                }
                 return PARALLEL;
             }
         };