Are two Java objects with same hashcodes not necessarily equal?

后端 未结 9 2107
礼貌的吻别
礼貌的吻别 2020-11-27 06:34

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

相关标签:
9条回答
  • 2020-11-27 07:20

    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.

    0 讨论(0)
  • 2020-11-27 07:21

    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.

    0 讨论(0)
  • 2020-11-27 07:24

    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.

    0 讨论(0)
提交回复
热议问题