equals : Java Glossary

go to home page E words local find full screen, hide local find menu Google search web for more information on this topic jump to foot of page translate this page with Babelfish 2008-06-12 by Roedy Green ©1996-2009 Canadian Mind Products
index page for letter ⇒ punctuation 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 (all)
equals
A method of Object for comparing two objects. If you don’t override equals, the default version simply compares the references, in other words even if all the fields in the two objects are identical the objects will still not compare as equal. They will compare as equal only when both references point to precisely the same object. This default equals is usually useless as the proverbial tits on a bull. You have to write your own equals to compare field by field, ignoring irrelevant fields. You can override equals like this:

Strategy

Here is a strategy for writing an equals method for some Object:
  1. Check for equality of the cached hashcodes. If they are not equal you know right away the two Objects can’t be equal.
  2. You then compare the two addresses/references. If equal, you know the entire Objects must be equal (the same).
  3. Failing that, you check the Object sizes. If they are not the same you know the two can’t be equal. There is no method to give you the aggregate Object size. By that I mean the sum of the lengths of the variable parts of the Object that participate in the equality test.
  4. Failing that, you do your byte by byte comparison.
Whenever you implement equals, you must also implement a matching hashCode.

Learning More

Sun’s Javadoc on the equals method : available:
Sun’s Javadoc on Arrays.deepEquals() : available:

CMP homejump to top
CMP logo
feedback Please email your feedback for publication, errors, omissions, broken/redirected link reports
and suggestions to improve this page to Roedy Green : feedback email
made with CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[65.110.21.43]
Your face IP:[38.103.63.58]
You are visitor number 30,300.
You can get a fresh copy of this page from: or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror)
http://mindprod.com/jgloss/equals.html J:\mindprod\jgloss\equals.html