Objects类学习
1.Objects类介绍
java.util.Objects类是操作对象的工具类,包含一些操作对象的静态方法,这些静态方法,这些静态方法可以防止NPE。
jdk1.7才开始有的。
2.Objects类的常用方法使用
2.1equals方法 可以防止NPE
该方法源码
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
equals判断两个对象是否相等,并且可以判断对象为null的。
String str1 = "abc";
String str2 = "bcd";
System.out.println(Objects.equals(str1, str2)); //false
String str1 = "bcd";
String str2 = "bcd";
System.out.println(Objects.equals(str1, str2)); //true
String str1 = null;
String str2 = "bcd";
System.out.println(str1.equals(str2)); // 报错 Exception in thread "main" java.lang.NullPointerException
String str1 = "null";
String str2 = "bcd";
System.out.println(Objects.equals(str1, str2)); //false
String str1 = null;
String str2 = null;
System.out.println(Objects.equals(str1, str2)); //true
2.2 nonNull 判断对象是否为空,空->false
2.2.1源码
public static boolean nonNull(Object obj) {
return obj != null;
}
2.2.2举例
Employee e = new Employee();
System.out.println(Objects.nonNull(e)); //true
System.out.println(Objects.nonNull(new Employee())); //true
Employee e = null;
System.out.println(Objects.nonNull(e)); //false
Employee employee = new Employee(15, "18801171255", "man", 888888888);
Employee employee1 = new Employee(18, "18801171255", "woman", 888888888);
Employee employee2 = new Employee(20, "18801171255", "man", 888888888);
Employee employee3 = null;
List<Employee> res = Arrays.asList(employee, employee1, employee2)
.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
Assert.assertEquals(Objects.nonNull(employee3),true);
// java.lang.AssertionError: expected:<false> but was:<true>