RFR: 8336043: Add quality of implementation discussion to Object.{equals, toString, hashCode}
Raffaello Giulietti
rgiulietti at openjdk.org
Thu Jul 11 14:47:56 UTC 2024
On Wed, 10 Jul 2024 22:33:54 GMT, Joe Darcy <darcy at openjdk.org> wrote:
> First pass at adding some quality of implementation discussions around the overridable methods of Object.
Here's a classical example of a directed acyclic graph (DAG, no cycles) consisting of 100 `ArrayList`s, each of size 2.
It takes some 1000x the _age of the universe_ to compute `hashCode()` or to compare two such DAGs with `equals()`, so no machine will ever come to completion.
And `toString()` throws an OOME because the results wouldn't fit in the limits of `String`.
This is to say that even without cycles and even with quite small data structures as here, we might encounter excessive resource usages in space or time by just invoking these methods.
(The same would hold by replacing `ArrayList` with a `record` of 2 components that does not override the default methods.)
import java.util.ArrayList;
public class DAG {
private static final int DEPTH = 100;
public static void main(String[] args) {
ArrayList<Object> dag0 = createSmallDAG();
ArrayList<Object> dag1 = createSmallDAG();
System.out.println(dag0.equals(dag1));
System.out.println(dag0.hashCode());
System.out.println(dag0);
}
private static ArrayList<Object> createSmallDAG() {
ArrayList<Object> n = growDAG(null);
for (int i = 1; i < DEPTH; ++i) {
n = growDAG(n);
}
return n;
}
private static ArrayList<Object> growDAG(ArrayList<Object> n) {
ArrayList<Object> m = new ArrayList<>();
m.add(n);
m.add(n);
return m;
}
}
-------------
PR Comment: https://git.openjdk.org/jdk/pull/20128#issuecomment-2223130481
More information about the core-libs-dev
mailing list