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

查看:113
本文介绍了比较两个对象并检查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(对象a,对象b)

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

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

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