Question

Is there any design pattern (or idiom) that helps to implement equals() method in Java?

That task is'n so hard but in most cases it's about the same... That's why I guess that there is a pattern but I didn't find it.

UPDATE

I chose the method: generate equals() method in Eclipse but... I found a good way (in AbstractList) to make that generated code better:

if (!(attributes ==null ? other.attributes==null : attributes.equals(other.attributes))) 
    return false; 

instead of generated:

if (attributes == null) {
        if (other.attributes != null)
        return false;
    } else if (!attributes.equals(other.attributes))
        return false;
Was it helpful?

Solution

Generally to implement equals() method, what I do is : I generate those from Eclipse as Eclipse can generate hashCode, toString and equals() methods very well.

OTHER TIPS

I always use following code:

if (null == obj) return false;
if (this == obj) return true;
if (!(object instanceof MyClass)) return false;
MyClass that = (MyClass) obj;
EqualsBuilder eb = new EqualsBuilder();
eb.append(this.businessKey, that.businessKey);
return eb.isEquals();

...

I never use technical keys like sequences or pk's, always business fields. Therefore I don't believe this can be made generic but must be made specific to any given Class.

It is pretty much up to yourself to decide when two object are "the same" in a certain sense... Should they be equal when they contain the same data (perfectly valid usecase) or more strictly when they are the same physical object in memory (also valid) or just the same row in a DB when compared in a clustered environment?

Just remember to also override .hashCode() or you're in for a world of hurt :-)

(Also, good article suggestions from @Andreas and @flash.)

Cheers,

Maybe this helps: Implementing equals. Especially be aware of the close relationship betweeen hashcode() and equals(). Other than that, I suppose the concrete implementation of equals() really depends on your class design, means when do you treat two objects equal.

Look at what Java Language Specification got to say.

equals method just defines the notion of object equality

Apart from that there is no design pattern involved in designing this method. The truth is that equals method is already designed by Java language designers and you can only make use of the design. If you are not confident of how to write your own equals method, consider taking the help of IDE's like eclipse which does the job for you.

Not sure about your expectation. equals() is meant for defining your criteria of comparing two different objects of your class for equality.

In general, you compare each attribute one by one but its very much possible and supported that you do the comparison using fewer selected attributes only.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top