How to compare two String objects in JAVA

problem

Recently written procedures, if encountered the need to compare two String objects are equal, I habitually wrote shaped like a if(a == "a"){}statement, IDEA out of the warning reads as follows:

String values are compared using '==', not 'equals()'.

In other words I just wrote that sentence should be if(a.equals("a")){}fishes, and she no longer marked red.

Explanation

So why is this so? ==And equals()respectively, what effect?

For basic data type byte(byte), short(short integer), int(integer), long(Long), float(single-precision floating-point), double(double precision floating point), boolean(Boolean), char(Character type), ==the comparison is their value, there is no equals()method.

For Stringthis type of data references, ==the comparison of a reference to the same memory address that is an address two objects, if the same memory address, the nature is the same object, like what's between the same object.

Our general scenario is mainly to compare the contents of two String objects, it would require the use of equals () method. We can look at the definition in java.lang.String equals () method, you can see the value is to compare two String objects in equals ().

/**
* Compares this string to the specified object.  The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* @param  anObject
*         The object to compare this {@code String} against
*
* @return  {@code true} if the given object represents a {@code String}
*          equivalent to this string, {@code false} otherwise
*
* @see  #compareTo(String)
* @see  #equalsIgnoreCase(String)
*/
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;
}

There is also a special case of the situation, such as "abcde" == "abcde"or "abcde" == "abc" + "de"will always return truebecause both sides are directly implemented by the compiler, it has not been declared as a variable.

summary

Of course, if you know what you are doing, it is to use == This feature, of course no problem. Other times with equals () method can be.

AMW Shi i: focus on research and knowledge of Java development technologies to share!

————END————
How to compare two String objects in JAVA

Guess you like

Origin blog.51cto.com/14409778/2423260