What's the quickest to compare two strings in Java?
Is there something faster than equals?
EDIT: I can not help much to clarify the problem.
I have two String which are sorted alphabetically and EXACTLY the same size
Example: abbcee and abcdee
Strings can be long up to 30 characters
To compare these strings in Java, we need to use the equals() method of the string. You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not.
There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.
The equals() tells the equality of two strings whereas the compareTo() method tell how strings are compared lexicographically.
Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.
I don't expect that Sun Oracle hasn't already optimized the standard String#equals()
to the max. So, I expect it to be already the quickest way. Peek a bit round in its source if you want to learn how they implemented it. Here's an extract:
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = count; if (n == anotherString.count) { char v1[] = value; char v2[] = anotherString.value; int i = offset; int j = anotherString.offset; while (n-- != 0) { if (v1[i++] != v2[j++]) return false; } return true; } } return false; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With