Wednesday, 30 July 2008

What is object equality in Java?

The Object class in Java has two methods that refer to equality: equals() and hashcode(). In general, if you override one of these methods, you must override both, as there are important relationships between the two.

Specifically? If two objects are equal according to equals() they must have the same hashcode() value (reverse not necessarily true).

if o1.equals(o2) then hashcode(o1) == hashcode(o2)

The default implementation of equals() provided by Object is reference equality:

public boolean equals(Object obj) {
return (this==obj);
}

This is a neater way of saying if(this==object) return true; return false;.

By this definition, 2 refs are equal only if they refer to the exact same object.

No comments: