用Objects.equals替换equals

equals方法我相信童鞋们必定不默认,字符串比较,对象比较都少不了这个方法,可是这个方法是会引发**NPE(NullPointerException)**的,因此总会有人告诉你把确信非空的放在前面比较,虽然这样会好不少,可是依旧可能出现NPE的状况。安全

噔噔噔噔,今天的主角出现了Objects.equals ,那它带着什么buff呢?我来给你简单介绍下。ide

  • 先来看下官方文档简介

public static boolean equals(Object a, Object b)
Returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.this

  • Parameters:
    a - an object
    b - an object to be compared with a for equality
  • Returns:
    true if the arguments are equal to each other and false otherwise
  • See Also:
    Object.equals(Object)

用我接近四级的中式英文为你们简单翻译一下:若是两个参数彼此equal返回true,不然返回false。固然若是两个参数都是null也返回true,其中一个为null则返回false。另外,是否相等是由第一个参数的equals方法来决定的。.net

能够看出它是个空指针安全方法,避免了原来的equals的NPE状况。单空的状况会返回false,咱们看下源码:翻译

public static boolean equals(Object a, Object b) {
              return (a == b) || (a != null && a.equals(b));
          }

这个相信你们一看就看明白了。指针

固然,最后仍是会用到equals方法,那这里扩展下,怎么样重写对象的equals方法。code

private int property_1;  
  private String property_2;  
    
  [@Override](https://my.oschina.net/u/1162528)  
  public boolean equals(Object o) {  
      if (this == o) return true;//指向同一个地址,引用相同,返回true
      if ((o == null) ||!(o instanceof ClassName)) return false; //若是O不是当前对象的实例,返回false 
      ClassName that = (ClassName) o;  
      return property_1 == that.getProperty_1() &&
      ( property_2 == that.getProperty_2() || (property_2.equals(that.getProperty_2());//比较两个对象的属性值,若是都相同也说明是一个对象,返回true
  }  
   // 重写equals方法必须重写hasCode方法
  [@Override](https://my.oschina.net/u/1162528)  
  public int hashCode() {  
      return Objects.hash(getProperty_1(), getProperty_2());  
  }

注意Objects.equals方法是JDK7新增的。对象

相关文章
相关标签/搜索