I understand why providing same hashcode for two equal (through equals
) objects is important. But is the vice versa true as well, if two objects have same hash
As a matter of fact
public int hashCode(){
return 1;
}
Is a valid hashcode implementation...but a terrible one. Will make all your hashtables slow. But yes, you can have two different objects with the same hashcode. But that should not be the general case, a real implementation should give different hashcodes for different values most of the time.
The purpose of the hashCode
function is allow objects to be quickly partitioned into sets of things that are known to unequal to all items outside their own set. Suppose one has 1,000 items and one divides them into ten roughly-equal-sized sets. One call to hashCode
could quickly identify the item as being not equal to 900 of the items, without having to use equals
on any of those items. Even if one had to use equals
to compare the item to 100 other items, that would still be only 1/10 the cost of comparing it to all 1000 items. In practice, even in a large collection, hashCode
will often eliminate 99.9% or more of the unequal items, leaving at most a handful to be examined.
hashCode
value depends on the implementation. for example String
class implements hashCode()
function depending upon the value. it means
String a=new String("b");
String b=new String("b");
will have same hashcode
but, these are two different objects. and a==b
will return false
.