Avid Programmer Avid Programmer - 4 years ago 136
Java Question

How is compareTo method from Java String Class efficient than the below code?

private static int myCompare(String a, String b) {

/* my version of the compareTo method from the String Java class */

int len1 = a.length();
int len2 = b.length();

if (len1 == len2) {

for (int i = 0; i < a.length(); i++) {

int intValueOfStringA = (int) a.charAt(i);
int intValueOfStringB = (int) b.charAt(i);

if (intValueOfStringA != intValueOfStringB) {

return intValueOfStringA - intValueOfStringB;
}
}
}
return -1;
}





EDIT:

I apologize for not framing my question properly the first time around. Going forth, I'll be more careful to precisely frame up my question. For my project, I needed a method that compared two strings to sort them alphabetically, so instead of googling (like most sane people) I quickly wrote one (and not a good one too). Going through the String Class, specifically the
compareTo
method, I found that it used more variables than I did. So, I was confused as to how that method was efficient than mine. Later on, I understood that it handles sorting much more efficiently than mine did. To elaborate, if two strings were of different length then my code would automatically return
-1
, which gives no information on whether or not the second string would precede or follow the first string.

Further, thanks to DM for pointing out that a String object obviously has direct access to its private variable and hands only a copy while making the
toCharAt
call, driving home the point that the
compareTo
method is indeed efficient and offers more utility than my temerarious
myCompare
method.

I was in a real hurry but also curious as to why the
compareTo
method was better than
myCompare
method, causing me to inadvertently rush with my question without any research or thought. LOL, the creators do know their methods. Like I said, in future, I'll research first and post better questions.

D M D M
Answer Source

Well, it appears that code 2 does use more memory. But that's because it uses toCharArray() which copies the contents of the Strings. The String compareTo() method has access to the private variables of String, and doesn't have to do that.

Other than that, they are very similar, although your method sorts primarily on String length instead of alphabetical order. I believe they would both be O(n) - they have to potentially check each character of both Strings. Code 2 also involves copying the characters in both Strings, but those are also O(n) operations, and O(n) + O(n) = O(n).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download