Can Java's hashCode produce same value for different strings?

前端 未结 12 852
情歌与酒
情歌与酒 2020-11-28 08:58

Is it possible to have same hashcode for different strings using java\'s hashcode function?or if it is possible then what is the % of its possibility?

12条回答
  •  死守一世寂寞
    2020-11-28 09:31

    Yes this is possible, because one of the contract between equals() & hashCode() method of Object class is.......... If two object are not equal according to equals() method then there is no guaranty that their hashCode will be same, the hashCode may/may not be equal. i.e, if obj1.equals(obj2) return false then obj1.hashCode()==obj2.hashCode() may/may not return true. Example:

        String str1 = "FB";
        String str2 = "Ea";
        System.out.println(str1.equals(str2));// false
        System.out.println(str1.hashCode() == str2.hashCode()); // true
    

提交回复
热议问题