Skip to main content

CSE 331: Equality

Two objects of an abstract data type are equal when they stand for the same abstract value, whatever their fields. Object's equals compares references, so a class whose objects stand for values writes its own, and every equals has to keep the five promises in Object's specification, which come free when it asks for the same abstract value. The one to write is equals(Object): an equals with any other parameter is an overload, picked by the argument's declared type, which @Override catches. hashCode is written beside it from the same value, or a HashSet loses track of equal objects. A subclass whose equals calls it equal to its superclass while telling its own objects apart breaks symmetry or transitivity, so a finer value gets its own class, by composition. Two implementations of one interface agree only when the interface specifies equals and every class writes it, and an object whose value changes while it sits in a HashSet is lost track of.