0

I saw a colleague write it as follows:

 @Override
 public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final ImageCode other = (ImageCode) obj;
    if ((this.code == null) ? (other.code != null) : !this.code.equals(other.code)) {
        return false;
    }
    return true;
}

Then, I suggested changing it for this:

@Override
public boolean equals(Object obj) {
    if (this == obj) {
         return true;
    }
    if (!(obj instanceof Parent)){
         return false;
    }
    final ImageCode other = (ImageCode) obj;
    if ((this.code == null) ? (other.code != null) : !this.code.equals(other.code)) {
         return false;
    }
    return true;
 }

but he told me that it is wrong, and that instanceof can't be used for the equals method. I don't understand why he said that.

Micho
  • 3,929
  • 13
  • 37
  • 40
lucare
  • 35
  • 6

2 Answers2

2

You can use instanceof in equals. Java uses it all the time. See e.g. String

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;

        // More code ...
        return true;
    }
    return false;
}
dejvuth
  • 6,986
  • 3
  • 33
  • 36
0

@dejvuth, If anObject is instance of String then why do we need to typecast. You can directly use it. I think its ok to go ahead without checking instanceOf. Just you may need to type cast the object. You can check my code here.

http://www.javavni.com/is-hashcode---and-equals---required-together.html

Rashmi
  • 271
  • 1
  • 2
  • 11