2

I have written a simple equals() method for a class:

@Override
public boolean equals(Object obj) { 
    if(obj instanceof Cl) {
        Cl u = (Cl)obj;
        return u.i == i;
    } else {
        return false;
    }
}

As I know, if I want compare if the class object equals to a null object, this returns false because of the instanceof, but according to my uni teacher this is a bad implementation, as the null check is missing. Can someone confirm for me if my theory is correct or not?

doncsoo
  • 35
  • 5
  • wont that throw NPE ? – Antoniossss Dec 18 '18 at 20:09
  • 3
    Your uni teacher is incorrect, `obj instaneof` is a `null` safe test (because `null` is only an instance of the NullType). https://stackoverflow.com/a/2707333/2970947 – Elliott Frisch Dec 18 '18 at 20:10
  • 1
    `cl` should be `Cl` or even better : a **relevant name**. Please follow Java naming conventions : packages, attributes, variables, parameters, method have to start in **lowerCase**, while class, interface should start in **UpperCase** – azro Dec 18 '18 at 20:11
  • @ElliottFrisch `null instanceof NullType` gives me false ;( No NPE though – Antoniossss Dec 18 '18 at 20:12
  • What is the type of `i`? If it's anything else than a primitive type, you might want to use `equals` for that, too. Otherwise this looks fine to me. – tobias_k Dec 18 '18 at 20:14
  • There is no type for which `null instanceof` will be true. Mainly because there is no way to get the NullType (which is not the same as the class you found) because it is deliberately not available for you to get. – Elliott Frisch Dec 18 '18 at 20:15
  • Here, this might clear it! https://stackoverflow.com/questions/2950319/is-null-check-needed-before-calling-instanceof – Swapnil Kesur Dec 18 '18 at 20:16
  • It’s a matter of taste. An explicit null check makes it clearer to the reader what happens in the code. I always have to think twice before I know what `null instanceof (SomeClass)` does. I don’t myself have any strong opinion either way. – Ole V.V. Dec 18 '18 at 20:39

1 Answers1

0

I think, a null check is not required and should not be there, because in this case there will not be any compile-time error or any exception if obj is null, because of the check if (obj instaceof C1).

Sul
  • 16