Barry
Barry

Reputation: 1665

Is this equals implementation ok?

I have a cache implementation for which i have the KeyObject implemented

So the cache is HashMap<KeyObject , List<SomeObjects>>

This KeyObject class ,say it has 2 variable a,b ;

class KeyObject {
    MyObject a;
    AnotherMyObject b;

    KeyObject(MyObject a, AnotherMyObject b){
          this.a = prop1 ; this.b= prop2;
    }
}

Is it ok , that i have equals method implemented depending on the properties on MyObject and AnotherMyObject..

Say something like this

public boolean equals(Object keyObject){
    if(keyObject.isSomeType() && this.a.isSomeType(){
       return keyObject.a.equals(this.a)
    }
    else{
        return keyObject.a.equals(this.a) && keyObject.b.equals(this.b)
    }
}

Is the equals implemenation like above a common practice?

Thanks

Upvotes: 1

Views: 74

Answers (2)

Anubian Noob
Anubian Noob

Reputation: 13596

Three things:

  1. Check if the object you are comparing to is null.
  2. Use instanceof to make sure the other object is of the right type.
  3. Type cast the other Object into a KeyObject before testing for equality.

So something like this:

// Override annotation gives you bonus points :)
@Override
public boolean equals(Object other) {
    if (other == null)
        return false;

    if (!(other instanceof KeyObject))
        return false;

    KeyObject keyObject = (KeyObject) other;

    // I'm not exactly sure what this line is doing
    // but I assume it's part of your program.
    if(keyObject.isSomeType() && this.a.isSomeType()
        return keyObject.a.equals(this.a);
    else
        return keyObject.a.equals(this.a) && keyObject.b.equals(this.b);
}

Upvotes: 3

Rannnn
Rannnn

Reputation: 582

I found this guide when googling: Implementing equals

  • object fields, including collections : use equals
  • type-safe enumerations : use either equals or == (they amount to the same thing, in this case)
  • possibly-null object fields : use both == and equals
  • array fields : use Arrays.equals
  • primitive fields other than float or double : use ==
  • float : convert to int using Float.floatToIntBits, then use ==
  • double : convert to long using Double.doubleToLongBits, then use ==

I think these guidelines are pretty much all your need.

Upvotes: 0

Related Questions