Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.equals implementation

In JDK 8, String.equals implements as

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

Why does the iteration uses two operations - incrementing i and decrementing n instead of something like that:

while (i < n) {
    if (v1[i] != v2[i])
        return false;
    i++;
}

or

while (i-- != 0) {
    if (v1[i] != v2[i])
        return false;
}

with one increment or decrement operation?

I suppose, it is somehow related to JVM bytecode optimization but don't understand how.

like image 533
Artem Zyuzko Avatar asked Nov 06 '15 13:11

Artem Zyuzko


People also ask

What does the equals () method do in strings?

The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.

Is the == is same as equals () in Java string handling?

equals() method in Java. Both equals() method and the == operator are used to compare two objects in Java. == is an operator and equals() is method. But == operator compares reference or memory location of objects in a heap, whether they point to the same location or not.

Can you use == with 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. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

How do you implement a string?

The most direct way to create a string is to write: String greeting = "Hello world!"; In this case, "Hello world!" is a string literal—a series of characters in your code that is enclosed in double quotes.


1 Answers

I think this is dead code, left over from the days when Strings still shared backing arrays and had offset and count, so that you needed to tweak the indexes a little.

The String implementation was changed in JDK 7 Update 6 (many people were upset about that, especially that it happened in a minor release). Strings don't share backing array anymore (unless the Strings are themselves equal, in which case a new deduplicator tries to re-share them).

You can see a discussion of the old implementation over at "how does String.equals() work".

like image 134
Thilo Avatar answered Oct 19 '22 06:10

Thilo