一道关于hashCode和equals的SCJP题
求助一道关于hashCode和equals的SCJP题Given:Java codeclass SortOf{String nameint balString codesho
求助一道关于hashCode和equals的SCJP题
Given:
Java codeclass 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是不对的。