One: the value is null

  1. a.equals(b)If a is null, throwNullPointExceptionThe exception.
  2. a.equals(b)A is not null, b is null, return false
  3. Objects.equals(a, b)Returns true if both a and B are null, false if either a or B is null and the other is not. Note: no null pointer exception is thrown.
null.equals("abc"Throw a NullPointerException"abc"To return to the equals (null)falseNull. Equals (null) → Raise NullPointerExceptionCopy the code
Objects.equals(null, "abc") - > returnfalse
Objects.equals("abc"To return, null)falseObjects.equals(null, null) → returntrue
Copy the code

Two: the value is an empty string

  1. Return true if a and B are both null strings: “”; return false if either a or B is not a null string;
  2. Objects.equals in this case behaves the same as in case 1.
"abc".equals("") - > returnfalse
"".equals("abc") - > returnfalse
"".equals("") - > returntrue
Copy the code
Objects.equals("abc"."") - > returnfalse
Objects.equals(""."abc") - > returnfalse
Objects.equals(""."") - > returntrue
Copy the code

Three: source code analysis

1. The source code.

public final class Objects {
    private Objects() {
        throw new AssertionError("No java.util.Objects instances for you!");
    }
 
    /** * Returns {@code true} if the arguments are equal to each other * and {@code false} otherwise. * Consequently, if both arguments are {@code null}, {@code true} * is returned and if exactly one argument is {@code null}, {@code * false} is returned. Otherwise, equality is determined by using * the {@link Object#equals equals} method of the first * argument. * * @param a an object * @param b an object to be compared with {@code a} for equality * @return {@code true} if the arguments are equal  to each other * and {@code false} otherwise * @see Object#equals(Object) */
    public static boolean equals(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));
    }
...
}
Copy the code

2. Show

First, the object address is determined. If it is true, no further determination is made.

If a is not null, then a is not null. If a is not null, then a is not null.

So, if both are null, it’s true on the first judgment. If it is not null, the address is different, and it is important to judge a. quals(b).

From: cnblogs.com/juncaoit