源码:
// Objects·类的equals方法,对两个对象进行比较,可以防止空指针异常
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
public class Demo03Objects {
public static void main(String[] args) {
String s1 = null;
String s2 = "abc";
boolean b = s1.equals(s2);
System.out.println(b);//java.lang.NullPointerException null是不能调用方法的,会抛出异常
}
}
使用Objects工具类:
public class Demo03Objects {
public static void main(String[] args) {
String s1 = null;
String s2 = "abc";
boolean b2 = Objects.equals(s1, s2);
System.out.println(b2);//false
}
}