apache / apache/lucene

equals methods should compare classes directly, not use instanceof [LUCENE-6744]

Open
#7,802 12 comments 0 reactions 0 assignees View on GitHub
legacy-jira-label:newdev legacy-jira-priority:Major type:bug
Dominant language
Java
Stars
3.6k
Forks
1.4k
Avg merge
2d 11h
Merged PRs (30d)
88

Description

from a 2015-07-12 email to the dev list from Fuxiang Chen...

```
We have found some inconsistencies in the overriding of the equals() method
in some files with respect to the conforming to the contract structure
based on the Java Specification.

Affected files:
1) ConstValueSource.java
2) DoubleConstValueSource.java
3) FixedBitSet.java
4) GeohashFunction.java
5) LongBitSet.java
6) SpanNearQuery.java
7) StringDistanceFunction.java
8) ValueSourceRangeFilter.java
9) VectorDistanceFunction.java

The above files all uses instanceof in the overridden equals() method in
comparing two objects.

According to the Java Specification, the equals() method must be reflexive,
symmetric, transitive and consistent. In the case of symmetric, it is
stated that x.equals(y) should return true if and only if y.equals(x)
returns true. Using instanceof is asymmetric and is not a valid symmetric
contract.

A more preferred way will be to compare the classes instead. i.e. if
(this.getClass() != o.getClass()).

However, if compiling the source code using JDK 7 and above, and if
developers still prefer to use instanceof, you can make use of the static
methods of Objects such as Objects.equals(this.id, that.id). (Making use of
the static methods of Objects is currently absent in the methods.) It will
be easier to override the equals() method and will ensure that the
overridden equals() method will fulfill the contract rules.
```

---
Migrated from [LUCENE-6744](https://issues.apache.org/jira/browse/LUCENE-6744) by Chris M. Hostetter (@hossman), updated Sep 15 2020
Attachments: [LUCENE-6744.patch](https://apache.github.io/lucene-jira-archive/attachments/LUCENE-6744/LUCENE-6744.patch) (versions: 2)
Pull requests: https://github.com/apache/lucene-solr/pull/1858, https://github.com/apache/lucene-solr/pull/1858, https://github.com/apache/lucene-solr/pull/1858

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.