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新增的。對象