RFR: 8335637: Add explicit well-behaved expectations to Object.{toString, hashCode}

Jaikiran Pai jpai at openjdk.org
Mon Jul 8 09:36:34 UTC 2024


On Sun, 7 Jul 2024 20:20:30 GMT, Joe Darcy <darcy at openjdk.org> wrote:

> Make well-behaved implementation expectations of Object.{toString, hashCode} explicit.

src/java.base/share/classes/java/lang/Object.java line 101:

> 99:      * implementation should not use excessive memory or time for its
> 100:      * computations and should return a result for cyclic data
> 101:      * structures.

Hello Joe, adding this text to set the expectations looks reasonable. However, I think the text "should return a result for cyclic data structures." feels a bit odd. If I understand correctly what it's trying to state is that for a class of the form:


class Foo {
   Bar bar;
   Foo self;
   
   public void setSelf() {
      this.self = this;
   }
}

then:


Foo foo = new Foo();
foo.toString(); // or foo.hashCode()

should be able to return the output from hashCode() and toString() even when an instance of `Foo` has a field which holds the same `Foo` instance. i.e. `toString()` and `hashCode()` should be able to handle re-entrancy and shouldn't consume excessive memory or time.

If that understanding is correct, then maybe we could improve that text to state it differently instead of cyclic data structures? I checked the JDK repo to see if this term has previously been used but it hasn't. Maybe we should just state that the hashCode() toString() methods should be able to deal with re-entrancy?

-------------

PR Review Comment: https://git.openjdk.org/jdk/pull/20063#discussion_r1668312734


More information about the core-libs-dev mailing list