-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathClassesOverrideEqualsAndHashCode.java
More file actions
56 lines (45 loc) · 1.55 KB
/
Copy pathClassesOverrideEqualsAndHashCode.java
File metadata and controls
56 lines (45 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
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
55
56
/*
Äàí êëàññ ComplexNumber. Ïåðåîïðåäåëèòå â íåì ìåòîäû equals() è hashCode() òàê, ÷òîáû equals() ñðàâíèâàë ýêçåìïëÿðû ComplexNumber ïî ñîäåðæèìîìó ïîëåé re è im, à hashCode() áûë áû ñîãëàñîâàííûì ñ ðåàëèçàöèåé equals().
Ïðèìåð
ComplexNumber a = new ComplexNumber(1, 1);
ComplexNumber b = new ComplexNumber(1, 1);
// a.equals(b) must return true
// a.hashCode() must be equal to b.hashCode()
*/
public final class ComplexNumber {
private final double re;
private final double im;
public ComplexNumber(double re, double im) {
this.re = re;
this.im = im;
}
public double getRe() {
return re;
}
public double getIm() {
return im;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ComplexNumber other = (ComplexNumber) obj;
if ((this.getRe() != other.getRe()) || (this.getIm() != other.getIm())) {
return false;
}
return true;
}
@Override
public int hashCode() {
long real = Double.doubleToLongBits(this.getRe()); // harmonize NaN bit patterns
long imag = Double.doubleToLongBits(this.getIm());
if (real == 1L << 63) real = 0; // convert -0.0 to +0.0
if (imag == 1L << 63) imag = 0;
long h = real ^ imag;
return (int)h ^ (int)(h >>> 32);
}
}