Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the quickest way to compare strings in Java?

Tags:

java

string

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

like image 354
Mediator Avatar asked Sep 27 '10 16:09

Mediator


People also ask

What is the best way to compare strings in Java?

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.

What are the 3 ways to compare two string objects?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.

What is difference between compareTo () and == in string?

The equals() tells the equality of two strings whereas the compareTo() method tell how strings are compared lexicographically.

How do you compare two strings in Java?

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.


1 Answers

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; } 
like image 149
BalusC Avatar answered Sep 20 '22 06:09

BalusC