equals() needed in most beans, entity/domain objects

Q: Suppose you are writing your own class C.java, and in other classes you plan to use List or Set. What method(s) do you need to write in C.java? What if you don’t write the method(s)?I know toString() is not something C.java must have.

A: equals(). Object.equals() uses reference comparison. Without overriding equals(), if you call Collection.contains() or Collection.remove(), you can’t pass in an identical carbon copy. A caron copy won’t pass contains() or remove().

Now most “noun” objects need to be usable in a collection and need meaninful contain() or remove() operations.

Note, once you override equals(), you need to override hashCode(). http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#equals(java.lang.Object). A Set and a Map are even more dependent on equals().

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s