I have just read in Effective Java that the fifth principle of the equals() method is that all objects must be unequal to null. The book goes on to say that some classes written by programmers guard against this using an explicit test for null:
public boolean equals(Object o){
if (o == null)
return false;
...
}
According to Effective Java, the above not null test is unnecessary. However, my question is, why then do so many programmers test for this not-nullity requirement?
You can do that with an instanceof test:
public boolean equals(Object o){
if (!(o instanceof MyObject))
return false;
...
}
null is not instance of anything, so this works.
Object firstObject = null;
secondObject.equals(firstObject);
how can you prevent this?? if you dont' check null before using it then it will crash. I think you will also need to check the class type like following
if (other == null || other.getClass() != this.getClass()) {
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With