Why does Java need equals () if hashCode ()?

If two objects return the same hashCode, doesn't that mean they are equal? Or do we need equals to prevent collisions?

And can I implement equals by comparing hashCodes?

+6
source share
7 answers

If two objects have the same hash code, they are NOT necessarily equal. Otherwise, you will find the perfect hash function. But the opposite is true - if the objects are equal, then they must have the same hash code.

+18
source

hashCode and Equals are different information about objects

Consider the analogy with people, where hashcode is Birthday,

escenario, b-day ( -), .

+9

hashCode, Oracle Docs, Java. - ( , int).

, , -. , .

class Test {

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

}

, equals -. , , -. , , o1.equals(o2), o1.hashCode() == o2.hashCode().

equals .

+3

-, , ?

, , .

javadocs Object :

hashCode :

  • , Java-, hashCode , equals ....
  • equals(Object), hashCode .
  • , equals(java.lang.Object), hashCode ....

. "" .


.

  • hashCode int.
  • 2 32 , int.
  • a.hashCode() == b.hashCode() a.equals(b), Java- 2 32 (.. ) .

. , , 2 32 java.lang.Object... 64- JVM.


, -.


, , , , .

  • Java equals.
  • equals, hashCode.

hashCode equals, hashCode , . .

+3

hashCodes β†’ β†’

hashCodes β†’ Object ( hashCode )

, equals. , -. , , , . hashCodes , , .

+2

Java equals(), hashCode()?

Java equals(), , , , , .

hashCode() - -; . - / . .

equals() hashCode() .

  • , -.
  • , -, , .

:

  • , -. , - .
  • , , - -; , .
  • hashCode() , JVM JVM.

JVM hashCode() , -, ; , , -.

equals hashCodes?

. , - .

+2

( ?) !

. .

SomeClass, , nInstanceCount :

iD = nInstanceCount++;

- ,

int hashCode(){
    return iD;
}

,

boolean equals( Object obj ){
    if( ! ( obj instanceof SomeClass )){
        return false;
    }
    return hashCode() == obj.hashCode();
}

... , "equals is overlluous" : , Java 10 ( Java 23) , , equals, ? ( NB ).

:

  • MAXINT SomeClass. ... ... . long, int... , hashCode() int.

  • "" , = , . . ...

, , , , , ""? : - "" , HashMap. : , "" , HashMap, . , , ( ) , hashCode()!

+1

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


All Articles