Java: Clean way of avoiding NullPointerException in equals checks

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

    You could do the following:

    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 equals(this.getStreet(),other.getStreet())
            && equals(this.getStreetNumber(), other.getStreetNumber())
            && equals(this.getStreetLetter(), other.getStreetLetter())
            && equals(this.getTown(), other.getTown());
    }
    
    private boolean equals(Object control, Object test) {
        if(null == control) {
            return null == test;
        }
        return control.equals(test);
    }
    

    Java 7 introduced built-in support for this use case with the java.util.Objects class see:

    • java.utils.Objects.equals(Object, Object)
    • java.utils.Objects.deepEquals(Object, Object)

提交回复
热议问题