2021-07-01

为什么不建议用 equals 判断对象相等?

作者:曹军

链接:www.cnblogs.com/juncaoit/p/12422752.html

一直以为这个方法是java8的,今天才知道是是1.7的时候,然后翻了一下源码。

这片文章中会总结一下与a.equals(b)的区别,然后对源码做一个小分析。

一,值是null的情况:

1.a.equals(b), a 是null, 抛出NullPointException异常。

2.a.equals(b), a不是null, b是null, 返回false

3.Objects.equals(a, b)比较时, 若a 和 b 都是null, 则返回 true, 如果a 和 b 其中一个是null, 另一个不是null, 则返回false。注意:不会抛出空指针异常。

null.equals("abc") → 抛出 NullPointerException 异常"abc".equals(null) → 返回 falsenull.equals(null)  → 抛出 NullPointerException 异常
Objects.equals(null, "abc") → 返回 falseObjects.equals("abc",null)  → 返回 falseObjects.equals(null, null)  → 返回 true

二,值是空字符串的情况:

1.a 和 b 如果都是空值字符串:"", 则 a.equals(b), 返回的值是true, 如果a和b其中有一个不是空值字符串,则返回false;

2.这种情况下 Objects.equals 与情况1 行为一致。

"abc".equals("") → 返回 false"".equals("abc") → 返回 false"".equals("")  → 返回 true
Objects.equals("abc", "") → 返回 falseObjects.equals("","abc")  → 返回 falseObjects.equals("","")  → 返回 true

三,源码分析

1.源码

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)); }

:http://lady.shaoqun.com/a/394627.html
观澜湖大地生态艺术园水上乐园门票多少钱:http://www.30bags.com/a/465615.html
"当一个女孩同意吃饭时,她就同意和一个男人睡觉."男人对性知识一无所知:http://lady.shaoqun.com/a/394628.html
婚后如何保持夫妻性生活和谐的秘诀:http://lady.shaoqun.com/a/394629.html

No comments:

Post a Comment