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.