Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not-nullity requirement or principle

Tags:

java

null

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?

like image 471
blackpanther Avatar asked Jun 04 '13 07:06

blackpanther


2 Answers

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.

like image 116
Joonas Pulakka Avatar answered Oct 18 '22 17:10

Joonas Pulakka


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;
        }
like image 22
stinepike Avatar answered Oct 18 '22 17:10

stinepike