SE450: Overriding: Equals [22/35] |
Equals in a final class (non-extendable concrete class).
Return true if for each field _f
:
this._f.equals(that._f)
final public class C { public boolean equals(Object thatObject) { if (!(thatObject instanceof C)) return false; C that = (C) thatObject; return ...; } }
Equals in an extendable concrete class.
public class C { public boolean equals(Object thatObject) { if ((thatObject == null) || (thatObject.getClass() != this.getClass())) return false; C that = (C) thatObject; return ...; } }
CompareTo sanity: (x.compareTo(y)<0
implies
y.compareTo(x)>0
)
final public class C { public int compareTo(Object thatObject) { C that = (C) thatObject; return ...; } } public class C { public int compareTo(Object thatObject) { if ((thatObject == null) || (thatObject.getClass() != this.getClass())) throw new ClassCastException(); C that = (C) thatObject; return ...; } }
An example of the problem.
file:Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package subclass.equals; class C1 { int i; public C1(int i) { this.i = i; } public boolean equals(Object thatObject) { if (!(thatObject instanceof C1)) return false; C1 that = (C1) thatObject; return that.i == this.i; } } class D1 extends C1 { int j; public D1(int i, int j) { super(i); this.j = j; } public boolean equals(Object thatObject) { if (!(thatObject instanceof D1)) return false; D1 that = (D1) thatObject; return that.i == this.i && that.j == this.j; } } class C2 { int i; public C2(int i) { this.i = i; } public boolean equals(Object thatObject) { if ((thatObject == null) || (thatObject.getClass() != this.getClass())) return false; C2 that = (C2) thatObject; return that.i == this.i; } } class D2 extends C2{ int j; public D2(int i, int j) { super(i); this.j = j; } public boolean equals(Object thatObject) { if ((thatObject == null) || (thatObject.getClass() != this.getClass())) return false; D2 that = (D2) thatObject; return that.i == this.i && that.j == this.j; } } public class Main { public static void main(String[] args) { C1 x1 = new C1(27); C1 y1 = new D1(27,42); System.out.println("x1==y1? " + (x1.equals(y1) ? "true" : "false")); System.out.println("y1==x1? " + (y1.equals(x1) ? "true" : "false")); C2 x2 = new C2(27); C2 y2 = new D2(27,42); System.out.println("x2==y2? " + (x2.equals(y2) ? "true" : "false")); System.out.println("y2==x2? " + (y2.equals(x2) ? "true" : "false")); } }