比较两个对象并检查 null [英] Compare two objects with a check for null

查看:20
本文介绍了比较两个对象并检查 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JDK 中是否有一种方法可以比较两个对象的相等性,并考虑空值?像这样:

Is there a method in the JDK that compares two objects for equality, accounting for nulls? Something like this:

public static boolean equals(Object o1, Object o2)
{
    if (o1 == null)
    {
        return o2 == null; // Two nulls are considered equal
    }
    else if (o2 == null)
    {
        return false;
    }

    return o1.equals(o2);
}

自己编写这个方法似乎很愚蠢,因为我认为它必须已经存在于某处.

It seems silly to write this method myself since I would think that it has to exist already somewhere.

推荐答案

Java 7.0 添加了一个新的方便的类:Objects.

Java 7.0 added a new handy class: Objects.

它有一个专门用于此的方法:Objects.equals(Object a, Object b)

It has a method exactly for this: Objects.equals(Object a, Object b)

这篇关于比较两个对象并检查 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆