Values of a value-based class such as LocalDate or Optional are compared with == or !=

tx0/java:value-based-identitydefaulterrorbug

What it finds

LocalDate, Instant, Duration, Optional and the other value-based classes of the JDK make no promise about identity: two equal values may or may not be the same object, as their documentation says, so == gives results that change between runs and versions. equals compares their values.

Reported is == or != between two operands of which one has one of these classes, by its declaration or creation, and neither is null, outside the JDK's own java. packages, which compare their cached instances on purpose.

From the rule's source, value_based_identity.rs.

Example from the rule's tests
import java.time.LocalDate;import java.util.Optional; class Dates {  boolean same(LocalDate a, LocalDate b, Optional<String> x, Optional<String> y, Object o) {    boolean p = a == b;tx0 reports: compares LocalDate values by identity    boolean q = x != y;tx0 reports: compares Optional values by identity    boolean r = a == null;    boolean s = a.equals(b);    boolean t = o == o;    return p || q || r || s || t;  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/java:value-based-identity" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:value-based-identity] reason="..."

tx0 explain tx0/java:value-based-identity shows the same in the terminal. Found a false positive? Report it.