views:

247

answers:

4

When writing one's own classes, is it always necessary to override equals(Object o)?

If I don't, will it automatically check that all the fields are the same? Or does it just check if the two variables point to the same object?

+11  A: 

If one is writing a class that is going to have its objects be compared in some way, then one should override the equals and hashCode methods.

Not providing an explicit equals method will result in inheriting the behavior of the equals method from the superclass, and in the case of the superclass being the Object class, then it will be the behavior setforth in the Java API Specification for the Object class.

The general contract for providing an equals method can be found in the documentation for the Object class, specifically, the documentation of the equals and hashCode methods.

coobird
+2  A: 

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the equals() method.You should always override the equals() method if the identity operator is not appropriate for your class.

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Warrior
+3  A: 

Only override equals() if it makes sense. But obviously if you override equals() you need to ensure that the hashcode() contract isn't broken, meaning if two objects are equal they must have the same hash code.

When does it make sense? When Object.equals() is insufficient. That method basically comes down to reference identity, meaning two objects are the same object so:

a.equals(b) iff q == b

Numbers are an obvious example when it makes sense because Integer(10) should equal another Intger(10).

Another example could be when you're representing database records. Let's say you have Student records with a unique integer ID, then it might be sufficient implementation of equals to simply compare the ID fields.

cletus
A: 

While you shouldn't rely on an IDE, Eclipse provides this canned functionality by pressing alt + shift + s and selecting the equals and hashCode menu options. There is also a toString option. Effective Java by Josh Bloch has good info on this subject. The link will take you to the chapter hosted on Google Books that discusses this topic.

Droo