Java: Clean way of avoiding NullPointerException in equals checks

前端 未结 8 1785
感情败类
感情败类 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:45

    I have a helper class Checker w/ a static method:

     public static boolean isEquals(final Object o1, final Object o2) {
            return o1 == null ? o2 == null : o1.equals(o2);
     }
    

    so, in the equals method,

     return Checker.isEquals(this.getStreet(), other.getStreet())
            && Checker.isEquals(this.getStreetNumber(), other.getStreetNumber())
            && Checker.isEquals(this.getStreetLetter(), other.getStreetLetter())
            && Checker.isEquals(this.getTown(), other.getTown());
    

提交回复
热议问题