Java Glossary : equals
Last updated 2004-06-28 by Roedy
Green ©1996-2004 Canadian Mind Products
Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
You are here : home : Java
Glossary : E words : equals.
- equals
- A method of Object for comparing two objects. You can override it like this:
/**
* Compare this Fruit object with another
* fruit object.
*
* @param other Object, usually a Fruit, to compare with.
*
* @return true if the objects are of identical flavour.
*/
public boolean equals ( Object other )
{
if ( other == null )
{
return false;
}
else if ( other instanceof Fruit )
{
return this.flavour.equals ((( Fruit )other ).flavour);
}
else return false;
}
-
Note that your method must work even when passed a null
or an Object of the "wrong" type.
-
Note that the method signature specifies Object. If
you change it to something else, you won't be overriding the official equals
method, but creating a new unrelated method that will only be used in some
contexts.
-
Whenever you implement an equals method, you must
implement a corresponding hashCode method.
-
The equals method implements an equivalence
relation. In other words, your equals method must
behave in a civilised way, behaving as people would expect a method called equals
ought to behave.
-
It must be reflexive: x.equals(x) should return true.
-
It must be symmetric: x.equals(y) should return true
if and only if y.equals(x).
-
It must be transitive: if x.equals(y) and y.equals(z),
then x.equals(z) should return true.
-
It must be consistent: multiple invocations of x.equals(y)
must consistently return true or consistently
return false, provided no information used in
equals comparisons on the object is modified.
What happens if your equals method violates these
rules or your hashCode method does not match your equals
method? Usually all that happens is the various collections such as Hashtable,
HashMap and HashSet don't
work. Java can't find the objects you put in the collections. Unfortunately, you
won't get a warning message explaining what you did wrong, so best to write a
little test code to make sure your methods behave according to the four rules.