Java Reference
In-Depth Information
It is reflexive
x.equals(x) must be true.
It is symmetrical
x.equals(y) must be true if and only if y.equals(x) is also true.
It is transitive
If x.equals(y) is true and y.equals(z) is true, then x.equals(z) must also be true.
It is repeatable
Multiple calls on x.equals(y) return the same value (unless state values used in the
comparison are changed, as by calling a set method).
It is cautious
x.equals(null) must return false rather than accidentally throwing a NullPointerEx-
ception .
In addition, beware of one common mistake: the argument to equals() must be declared as
java.lang.Object , not the class it is in; this is so that polymorphism will work correctly
(some classes may not have an equals() method of their own). To prevent this mistake, the
@Override annotation was designed, as mentioned in Beyond Javadoc: Annotations/
Metadata .
Here is a class that endeavors to implement these rules:
public
public class
class EqualsDemo
EqualsDemo {
private
private int
int int1 ;
private
private SomeClass obj1 ;
/** Constructor */
public
public EqualsDemo ( int
int i , SomeClass o ) {
int1 = i ;
iif ( o == null
null ) {
throw
throw new
new IllegalArgumentException ( "Data Object may not be null" );
}
obj1 = o ;
}
Search WWH ::




Custom Search