Is it legal?

I came across this piece of code. I have never seen equals realized this way. I was struck by the fact that it is really "tidy" in the sense that it accepts only one line of the template.

However, the fact that I never saw such an approach before making me suspicious. According to the Java equals and hashCode contract, is the following implementation legal?

@Override
public boolean equals(Object o)
{
  return this == o || o instanceof DetailsPageTrackingRequest 
  && this.hashCode() == o.hashCode();
}

@Override
public int hashCode()
{
  //java.util.Objects
  return Objects.hash(pageTrackingRequest, searchId, productId);
}
+1
source share
4 answers

This is probably a bad idea for the reasons already outlined in the other answers.

Regarding the “legal” aspects, Contract of Object.equals claims

equals :

  • : , x.equals() .
  • : x y x.equals(y) true , y.equals(x) true.
  • : x, y z, x.equals(y) true, y.equals(z) true, x.equals(z) true.
  • : x y x.equals(y) true false, , , .
  • , x.equals(NULL) .

:

  • reflexive: , - this == o
  • : - instanceof - .
  • : ,
  • :
  • x.equals(null) false: , - instanceof

, , , - . getClass() over instanceof .equals()?.

, , hashCode , .


:

x y

class Point {
    final int x;
    final int y

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

- > 2^32 * 2^32 = 2^64 , 2^32 -. , , equals.


. equals hashCode: Objects.hash? -, - , Objects.hash Strings.

+1

, .

, pageTrackingRequest, searchId productId -, . equals , 3 .

+5

, hashCode. , objects hashCode, .

, equals hashCode, . hashCode :

@Override
public int hashCode()
{
    return 31;
}

equals true , .

+1
source

This approach is incorrect. Hash code equality is not convincing, since unequal objects can have the same hash. This is a built-in error.

0
source

Source: https://habr.com/ru/post/1015791/


All Articles