关于html:为什么-不建议用-equals

37次阅读

共计 1608 个字符,预计需要花费 5 分钟才能阅读完成。

这片文章中会总结一下与 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) → 返回 false
null.equals(null) → 抛出 NullPointerException 异样
Objects.equals(null, “abc”) → 返回 false
Objects.equals(“abc”,null) → 返回 false
Objects.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”, “”) → 返回 false
Objects.equals(“”,”abc”) → 返回 false
Objects.equals(“”,””) → 返回 true
三,源码剖析
1. 源码
//java fhadmin.cn
public final class Objects {

private Objects() {throw new AssertionError("No java.util.Objects instances for you!");
}

/**
 * Returns  if the arguments are equal to each other
 * and  otherwise.
 * Consequently, if both arguments are {@code null}, {@code true}
 * is returned and if exactly one argument is {@code null}, {@code
 * false} is returned.  www.sangpi.comOtherwise, equality is determined by using
 * the {method of the first
 * argument.
 *
 * 
 * @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));
}

2. 阐明
首先,进行了对象地址的判断,如果是真,则不再持续判断。

如果不相等,前面的表达式的意思是,先判断 a 不为空,而后依据下面的知识点,就不会再呈现空指针。

所以,如果都是 null,在第一个判断上就为 true 了。如果不为空,地址不同,就重要的是判断 a.equals(b)。

四,“a==b”和”a.equals(b)”有什么区别?
如果 a 和 b 都是对象,则 a==b 是比拟两个对象的援用,只有当 a 和 b 指向的是堆中的同一个对象才会返回 true。

而 a.equals(b) 是进行逻辑比拟,当内容雷同时,返回 true,所以通常须要重写该办法来提供逻辑一致性的比拟。

正文完
 0