Java: Clean way of avoiding NullPointerException in equals checks

前端 未结 8 1545
感情败类
感情败类 2021-02-12 12:27

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):



        
8条回答
  •  孤独总比滥情好
    2021-02-12 12:42

    Google Guava provides Objects.equal(Object, Object) which checks for equality while taking into consideration that either of the parameters might be null:

    ...
    return Objects.equal(this.getStreet(), other.getStreet())
        && Objects.equal(this.getStreetNumber(), other.getStreetNumber())
        && Objects.equal(this.getStreetLetter(), other.getStreetLetter())
        && Objects.equal(this.getTown(), other.getTown());
    

    It's also worth pointing out that Objects has other helper methods for implementing hashCode() and toString().

提交回复
热议问题