equals and hashCode

Aleksey Shipilev aleksey.shipilev at oracle.com
Tue Oct 30 04:15:08 PDT 2012

On 10/26/2012 11:38 PM, Brian Goetz wrote:
> Yes, it is decided: lambdas will inherit the implementation of 
> equals/hashCode from Object.  So, that means no relief for the use case 
> you are raising here.

Just to clarify, because someone else was asking me this.

That means lambdas inherit the default implementations of
equals/hashCode? It is as saying "you can't rely on equals()/hashCode()
for lambdas, since you are not in control of those". Although one can
piggyback on the factual behavior of lambdas, and we would have to
explicitly say when the lambdas are considered to be equal (or not). I.e.:

 Mapper lam1 = (x) -> x + 1;
 Mapper lam2 = (x) -> x + 1;
 Mapper mref1 = ((Integer)0)::compareTo;
 Mapper mref2 = ((Integer)0)::compareTo;
 Mapper mref3 = (new Integer(0))::compareTo;
 Mapper mref4 = (new Integer(0))::compareTo;
 Mapper smref1 = Integer::parseInt;
 Mapper smref2 = Integer::parseInt;

What are the expectations for equality? If we just inherit the default
equals/hashCode, I would expect:

 assertEquals(lam1, lam1);     // true
 assertEquals(lam1, lam2);     // false
 assertEquals(mref1, mref1);   // true
 assertEquals(mref1, mref2);   // false
 assertEquals(mref3, mref3);   // true
 assertEquals(mref3, mref4);   // false
 assertEquals(mref1, mref3);   // false
 assertEquals(smref1, smref2); // true (?)

I would take a wild guess this does not prevent making lambda "not
objects" if some runtime decides to get away from this. Since there's no
way to implement equals()/hashCode(), the only requirement is to make
the lambdas/mrefs to act equal if they are captured at the same site?

For the captures, this seems complicated:

class A {
 final int y;

 Mapper m() {
    return (x) -> x + y; // captures "this"

class B {
 foo() {
    A a1 = new A();
    A a2 = new A();
    assertEquals(a1.m(), a1.m()); // naively want to be true, is it?
    assertEquals(a1.m(), a2.m()); // false


More information about the lambda-dev mailing list