Objects类学习

Objects类在Java中提供了一些实用的静态方法,如equals和nonNull,用于安全地比较和检查对象。equals方法避免了NullPointerException(NPE),通过首先检查对象是否为空再进行比较。nonNull方法则判断对象是否为空,返回布尔值。这两个方法在处理可能为null的对象时能有效防止程序异常。示例代码展示了它们的使用和效果。
摘要由CSDN通过智能技术生成

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

boy快快长大

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值