equals方法我相信童鞋们一定不默认,字符串比较,对象比较都少不了这个方法,但是这个方法是会引起**NPE(NullPointerException)**的,所以总会有人告诉你把确信非空的放在前面比较,虽然这样会好很多,但是依旧可能出现NPE的情况。
噔噔噔噔,今天的主角出现了Objects.equals ,那它带着什么buff呢?我来给你简单介绍下。
- 先来看下官方文档简介
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.
- 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方法来决定的。
可以看出它是个空指针安全方法,避免了原来的equals的NPE情况。单空的情况会返回false,我们看下源码:
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
这个相信大家一看就看明白了。
当然,最后还是会用到equals方法,那这里扩展下,怎么样重写对象的equals方法。
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新增的。