Skip to content

Commit e671d63

Browse files
author
Nicolai Parlog
committed
Show how to use instanceof to implement equals
1 parent 39fc3da commit e671d63

File tree

1 file changed

+35
-0
lines changed
  • src/main/java/org/codefx/demo/java16/lang/instanceof_

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
}

0 commit comments

Comments
 (0)