日期:2014-05-20  浏览次数:20722 次

求助一道关于hashCode和equals的SCJP题
Given:
Java code

class SortOf{
    String name;
    int bal;
    String code;
    short rate;
    
    public int hashCode(){
        return (code.length() * bal);
    }
    public boolean equals(Object o){
        //insert code here
    }
}


Which of the following will fulfill the equals() and hashCode() contracts for this class?
(Choose all that apply)
A return ((SortOf)o).bal == this.bal;
B return ((SortOf)o).code.length() == this.code.length();
C return ((SortOf)o).code.length() * ((SortOf)o).bal == this.code.length() * this.bal;
D return ((SortOf)o).code.length() * ((SortOf)o).bal * ((SortOf)o).rate == this.code.length() * this.bal * this.rate;

标准答案为:C、D
我认为答案为C,因为D可能造成equals()返回为true而hashCode返回为false的情况。
请教各位答案,以及原因。

------解决方案--------------------
期待真相
------解决方案--------------------
按照规定,equals相等的对象,hashcode值也要相等,反过来不一定
------解决方案--------------------
我也觉得d不对
------解决方案--------------------
D不会造成equals相等而hashcode不一样的情况
------解决方案--------------------
显然D是不对的。

------解决方案--------------------
如果有两个对象
aInstance
code=“abcd”//lenght=4
bal=2
rate=3

bInstance
code="efgh"//length =4
bal=3
rate=2

如果按照D
((SortOf)o).code.length() * ((SortOf)o).bal * ((SortOf)o).rate =4*2*3=4*3*2=24
也就是说equls相等
但此时aInstance的hashcode=4*3=12
bInstance 的hashcode=4*2=8
也就是说当equals相等时这两个对象的hashcode不相等。所以显然D是不对的。