Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the equals() method works

Tags:

java

equals

I am digging into the basics of Java. I infer from this article, that the Java 'equals' method means, if two objects are equal then they must have the same hashCode().

Here's my example.

public class Equals {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String a = new String("a");
        String b = new String("a");
        System.out.println("a.hashCode() "+a.hashCode());
        System.out.println("b.hashCode() "+b.hashCode());
        System.out.println(a == b);
        System.out.println(a.equals(b));
    }

}

Output:

a.hashCode() 97
b.hashCode() 97
false
true

The actual Java language 'equals' method:

  public boolean equals(Object obj) {
    return (this == obj);
  }

In my above example, a.equals(b) has returned true, meaning the condition 'a==b' is satisfied. But then why is 'a==b' returning false in that example?

Aren't hashCode and address one and same? Also, is 'hashCode' compared when we say 'a==b' or something else?

like image 998
srk Avatar asked Apr 18 '13 17:04

srk


2 Answers

The == operator in Java compares object references to see if they refer to the same object. Because your variables a and b refer to different objects, they are not equal according to ==.

And the hashCode method doesn't return the address in String, because that class has overridden hashCode.

Additionally, the equals method has been implemented in String to compare the contents of the strings; that's why a.equals(b) returns true here.

like image 52
rgettman Avatar answered Nov 05 '22 08:11

rgettman


The String class has overridden the equals() method. Please follow the String equals() documentation.

a.equals(b) has returned true, meaning the condition a==b is satisfied

This is the default implementation of equals() in the Object class, and the String class has overridden the default implementation. It returns true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

Aren't hashCode and address one and same?

Not necessarily. For further reading on hashCode().

like image 29
AllTooSir Avatar answered Nov 05 '22 08:11

AllTooSir