File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
src/main/java/org/codefx/demo/java16/lang/instanceof_ Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ package org .codefx .demo .java16 .lang .instanceof_ ;
2
+
3
+ import java .util .Objects ;
4
+
5
+ import static java .util .Objects .requireNonNull ;
6
+
7
+ /**
8
+ * Pattern matching in {@code if} works great for implementing {@code equals}.
9
+ */
10
+ public class Equals {
11
+
12
+ private final String someField ;
13
+ private final String anotherField ;
14
+
15
+ public Equals (String someField , String anotherField ) {
16
+ this .someField = requireNonNull (someField );
17
+ this .anotherField = requireNonNull (anotherField );
18
+ }
19
+
20
+ @ Override
21
+ // note that an `equals` implementation that uses `instanceof`,
22
+ // should be final to prevent subclasses from overriding it,
23
+ // which usually breaks symmetry or transitivity
24
+ public final boolean equals (Object o ) {
25
+ return o instanceof Equals other
26
+ && someField .equals (other .someField )
27
+ && anotherField .equals (other .anotherField );
28
+ }
29
+
30
+ @ Override
31
+ public int hashCode () {
32
+ return Objects .hash (someField , anotherField );
33
+ }
34
+
35
+ }
You can’t perform that action at this time.
0 commit comments