Java: Clean way of avoiding NullPointerException in equals checks

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

    I'd consider defining some of the equals methods as static class methods, like say for the Street objects. This way you don't ever attempt to call the .equals() method on a null.

    A sample function might look like:

    public static boolean equals(Object one, Object two)
    

    Also, it's good practice to put checks like

    if (obj == null)
       return false;
    

    at the very beginning of a function.

提交回复
热议问题