2.5.1

question:

Consider the following implementation of the compareTo() method for String. How does the third line help with efficiency?

public int compareTo(String that)
{
    if(this == that) return 0;//this line
    int n = Math.min(this.length(), that.length());
    for(int i = 0; i < n; i++)
    {
        if(this.charAt(i) < that.charAt(i)) return -1;
        else if(this.charAt(i) > that.charAt(i)) return +1;
    }
    return this.length() - that.length();
}

answer:

//官网答案

Solution: it avoid directly comparing individual characters if s and t are references to the same string.

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9145711.html