| Author |
About equals and hashCode contract
|
Helen Ma
Ranch Hand
Joined: Nov 01, 2011
Posts: 319
|
|
I was doing a quiz from the exam simulator from Kathy and Bert's study guide, here is the quiz:
public 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
}
}
Two of the Choices:
c . ((SortOf)o).length()* ((SortOf)o) == this.code.length() * this.bal
d . ((SortOf)o).code.length()* ((SortOf)o).bal * ((SortOf)o).rate== this.code.length()* this.bal * this.rate
I think choice d is not right in my opinion. Let's say o has 5,3,1 for code length, bal and rate and this instance has 1, 3,5 correspondingly.
When two SortOf objects are equals based on choice d, their hash codes should be the same. However, the hash codes are 15 and 3 based on hashCode() method.
Therefore, when we are asked which choice satisfy the equal and hashcode contract, c is the only choice. However, the suggested solution is c and d.
Can anyone explain to me why d is the answer?
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 2686
|
|
Helen Ma wrote:Can anyone explain to me why d is the answer?
That's a popular question this week.
|
Joanne
|
 |
 |
|
|
subject: About equals and hashCode contract
|
|
|