Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Clean way of avoiding NullPointerException in equals checks

Tags:

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()); } 

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?

like image 235
Svish Avatar asked Apr 14 '11 10:04

Svish


1 Answers

You can use a helper method like

public static boolean isEqual(Object o1, Object o2) {     return o1 == o2 || (o1 != null && o1.equals(o2)); } 
like image 91
Peter Lawrey Avatar answered Nov 10 '22 00:11

Peter Lawrey