I need to implement equals() and hashCode()
for an Address
class.
I believe,the non null fields are taken to determine hashCode() and equals().In my application,Any of the fields except addressLine1
and country
can be null.If that is the case,what happens if two different addresses have the same addressline1 and country?
Address1:(in state of NH which is omitted by user)
addressline1:111,maple avenue
country: US
Address2:
addressline1:111,maple avenue
state: Illinois
country: US
In such cases if I build a hashCode based only on non null fields ,it will give same for both addresses above.
Is this the right way to create hashCode?
int hash = addressline.hashCode();
if(addressLine2!=null){
hash += addressLine2.hashCode();
}
and so on...