explain equals() for Object

hello,
can anyone explain how does equals() works for Object ?
I understand that Object are equals only if they share the same hashCode ?
and so to explain hashCode & overide thing (if it is linked)
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#clone()
thank you

String us[] = {"a", "b", "c"};
String them[] = us.clone() ; 

println("us hashcode : "+us.hashCode() );
println("them hashcode : "+them.hashCode() );
println(us.equals(them)) ; // return false

Answers

  • edited March 2016 Answer ✓
    • Both methods equals() & hashCode() belong to class Object.
    • Since all Java classes (even arrays) implicitly inherits from Object, all of its methods are also available to them.
    • When any object is created, a contiguous block of memory is allocated for it.
    • Its 1st memory address is called reference or pointer. And it's unique for each object in a given moment.
    • By default, equals() acts the same as equality operator ==. That is, it compares the values of 2 references.
    • Since each object has its own unique reference value, Object's original equals() always return false for diff. objects, regardless whether both got exactly the same content.
    • Method clone() creates a new object w/ the same content as the original.
    • Unfortunately arrays don't @Override equals(). Therefore cloned arrays are always false when compared against the original or even to each other, b/c each 1 got a unique memory address.
    • But fret not, static method equals() from class Arrays can do the job instead: :-bd
      http://docs.Oracle.com/javase/8/docs/api/java/util/Arrays.html#equals-java.lang.Object:A-java.lang.Object:A-

    println(java.util.Arrays.equals(us, them)); // returns true

  • okay and hasCode() return the reference of the object ?

  • Better read their explanation for it:
    https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode--

    As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)

  • okay. lets said a "representation" of the reference (or pointer) of the Object.
    thx u , its clearer

Sign In or Register to comment.