1/**
2 * Similar to compareTo method But compareTo doesn't return correct result for string+integer strings something like `A11` and `A9`
3*/
4
5private int newCompareTo(String comp1, String comp2) {
6 // If any value has 0 length it means other value is bigger
7 if (comp1.length() == 0) {
8 if (comp2.length() == 0) {
9 return 0;
10 }
11 return -1;
12 } else if (comp2.length() == 0) {
13 return 1;
14 }
15 if (TextUtils.isDigitsOnly(comp1)) {
16 int val1 = Integer.parseInt(comp1);
17 if (TextUtils.isDigitsOnly(comp2)) {
18 int val2 = Integer.parseInt(comp2);
19 return Integer.compare(val1, val2);
20 } else {
21 return comp1.compareTo(comp2);
22 }
23
24 } else {
25
26 int minVal = Math.min(comp1.length(), comp2.length()), sameCount = 0;
27
28 // Loop through two strings and check how many strings are same
29 for (int i = 0;i < minVal;i++) {
30 char leftVal = comp1.charAt(i), rightVal = comp2.charAt(i);
31 if (leftVal == rightVal) {
32 sameCount++;
33 } else {
34 break;
35 }
36 }
37 if (sameCount == 0) {
38 return comp1.compareTo(comp2);
39 } else {
40 String newStr1 = comp1.substring(sameCount), newStr2 = comp2.substring(sameCount);
41 if (TextUtils.isDigitsOnly(newStr1) && TextUtils.isDigitsOnly(newStr2)) {
42 return Integer.compare(Integer.parseInt(newStr1), Integer.parseInt(newStr2));
43 } else {
44 return comp1.compareTo(comp2);
45 }
46 }
47 }
48}
1num == Integer.parseInt(str) is going to faster than str.equals("" + num)
2
3str.equals("" + num) will first convert num to string which is O(n) where n being the number of digits in the number. Then it will do a string concatenation again O(n) and then finally do the string comparison. String comparison in this case will be another O(n) - n being the number of digits in the number. So in all ~3*O(n)
4
5num == Integer.parseInt(str) will convert the string to integer which is O(n) again where n being the number of digits in the number. And then integer comparison is O(1). So just ~1*O(n)
6
7To summarize both are O(n) - but str.equals("" + num) has a higher constant and so is slower.