quals检查中避免NullPointerException的干

quals检查中避免NullPointerException的干

本文介绍了Java:在equals检查中避免NullPointerException的干净方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个地址对象,我想为其创建一个 equals 方法.我可以通过执行以下操作(缩短一点)来使这变得非常简单:

I have an address object that I want to create an equals method for. I could have made this quite simple by doing something like the following (shortened a bit):

public boolean equals(Object obj)
{
    if (this == obj)
        return true;

    if (obj == null)
        return false;

    if (getClass() != obj.getClass())
        return false;

    Address other = (Address) obj;

    return this.getStreet().equals(other.getStreet())
        && this.getStreetNumber().equals(other.getStreetNumber())
        && this.getStreetLetter().equals(other.getStreetLetter())
        && this.getTown().equals(other.getTown());
}

问题是,其中一些可能为空.换句话说,如果这个地址中没有街道字母,我会得到一个 NullPointerException.

Problem is, some of these might be null. I will in other words get a NullPointerException if there is no street letter in this address.

如何在考虑空值的同时以干净的方式编写此代码?

How can I write this in a clean way while taking null values into account?

推荐答案

你可以使用像

public static boolean isEqual(Object o1, Object o2) {
    return o1 == o2 || (o1 != null && o1.equals(o2));
}

这篇关于Java:在equals检查中避免NullPointerException的干净方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 01:46