Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of ==, equals and hashcode in java

Given this:

String s1= new String("abc");
String s2= new String("abc");
String s3 ="abc";
System.out.println(s1==s3);
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());

Output is:

false
false
true
true
96354
96354
96354

Here == is giving false for each object but the hashcode for each String object is same. Why is it so?

like image 431
Abhishek Jain Avatar asked Apr 28 '10 17:04

Abhishek Jain


2 Answers

== does compare real equality of objects (I mean - both references point to the same object), not their content, whereas .equal compares content (at least for String).

String a = new String("aa");
String b = new String("aa"); 

a and b are pointing to different objects.

Notice also that if objects are equal then their hashchodes must be the same, but if hashcodes are the same, it doesn't mean that objects are equal.

like image 114
Mirek Pluta Avatar answered Sep 30 '22 05:09

Mirek Pluta


The equals contract says that if o1.equals(o2), then o1.hashCode() == o2.hashCode(). It doesn't specify anything about the hash codes of unequal objects. You could have a method like

public int hashCode()
{
    return 42;
}

and it'd fulfill the contract. It's just expected that the hash code be related to the value of the object, in order to make hash tables work more efficiently.

Now, as for why your == doesn't work, two objects will always be compared by reference. That is, if o1 == o2, then o1 and o2 are the exact same object. That's rarely what you want; you usually want to see if o1.equals(o2) instead.

like image 25
cHao Avatar answered Sep 30 '22 04:09

cHao