Java null.equals(对象o) [英] Java null.equals(object o)

查看:57
本文介绍了Java null.equals(对象o)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道不可能在这样的空对象上调用equals方法:

I know it's not possible to call the equals method on a null object like that:

//NOT WORKING
            String s1 = null;
            String s2 = null;
            if(s1.equals(s2))
            {
                System.out.println("NOT WORKING :'(");
            }

但是在我的情况下,我想比较两个数据库中的两个对象,这两个对象的属性可以为null ...

But in my case I want to compare two objects from two database and these two objects can have attributes null...

在不知道值是否为null或填充的情况下,比较两个属性的方法是什么?

So what is the method to compare two attributes, knowing that we are not sure that the value is null or filled.

这个方法好不好?

//WORKING
            String s1 = "test";
            String s2 = "test";
            if(s1 == s2 || s1.equals(s2))
            {
                System.out.println("WORKING :)");
            }

            //WORKING
            String s1 = null;
            String s2 = null;
            if(s1 == s2 || s1.equals(s2))
            {
                System.out.println("WORKING :)");
            }

我不确定,因为在这种情况下它不起作用...:

I'm not sure because in this case it's not working ... :

//NOT WORKING
            String s1 = null;
            String s2 = null;
            if(s1.equals(s2)|| s1 == s2  )
            {
                System.out.println("NOT WORKING :'''(");
            }

推荐答案

我通常使用我编写的称为 equalsWithNulls 的静态实用程序函数来解决此问题:

I generally use a static utility function that I wrote called equalsWithNulls to solve this issue:

class MyUtils {
  public static final boolean equalsWithNulls(Object a, Object b) {
    if (a==b) return true;
    if ((a==null)||(b==null)) return false;
    return a.equals(b);
  }
}

用法:

if (MyUtils.equalsWithNulls(s1,s2)) {
  // do stuff
}

这种方法的优点:

  • 在单个函数调用中解决了完全相等性测试的复杂性.我认为这比每次执行此操作时在代码中嵌入一堆复杂的布尔测试要好得多.结果导致错误的可能性要小得多.
  • 使您的代码更具描述性,因此更易于阅读.
  • 通过在方法名称中明确提及null,您向读者传达了他们应该记住的一个或两个参数可能为null的信息.
  • 首先进行(a == b)测试(该优化避免了在a和b为非空但引用完全相同的对象的相当普遍的情况下避免调用a.equals(b)的情况)

这篇关于Java null.equals(对象o)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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