3

I have a base class for multiple data object types in Java. I want to create an equals method in the base class, that works directly when inherited.

Equality is determined by the two objects

  1. belonging to subclasses of the base class. This is easily achievable using

    if (!(anObject instanceof BaseClass))
        return false;
    
  2. having the same ID. The ID field is defined by the base class so we can here test that.

    if (this.id != ((BaseClass) anObject).id)
        return false;
    
  3. belonging to the same class. This is where I have the problem. Two objects may be of different types (and so be in different lists), but have the same ID. I have to be able to distinguish them. How can I do this?

PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58

5 Answers5

9

Use

this.getClass() == anotherObject.getClass()

instead of instanceof. This will return true only if the two object belong to the same class (it's safe to check if class objects are equal by reference). And after that you may compare the id.

user2660000
  • 332
  • 2
  • 3
1

You should read this article for problems when implementing equals.

To make it short: use this.getClass()==other.getClass() instead of instanceof, because otherwise the equals() relationship will not be transitive (superInstance.equals(subInstance) will be true, but subInstance.equals(superInstance) will be false).

V G
  • 18,822
  • 6
  • 51
  • 89
0

If I understand you question correctly, you need a way to differentiate two objects of same Class with same id. If so, for this you may use toString() which gives unique representation of objects unless they are string objects. Of course, you must not have overridden toString() in your base class. example:You can use this, only for the third case that you mentioned.

if (this.toString()!= anObject.toString())
    return false;
-1

You can do that with Class.isInstance() method. In your base class, do this.

public static boolean isAnInstance(Object obj)
{
    return BaseClass.class.isInstance(obj);
}

Then you can check

if (BaseClass.isAnInstance(object))
{
    // Class of object is 'BaseClass' or
    // it extends the 'BaseClass'
}

Hope this helps.

Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91
-1

The best practice to know objects equality is to override hashcode() and equals() if you maitain objects in a collection

you can refer Why do we have to override the equals() method in Java?

Community
  • 1
  • 1
ksv
  • 37
  • 5