The Question 56 is:
Given:
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 fullfil the equals() and hashCode() contracts for this class? (Choos 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 and D are given as the correct answers.
I agree C is correct. But, If I create the SortOf class with answer D and run the following code, I get true and false. So, the hashCode() returns a different value when the objects are equal. Does that mean the correct answer is C only?
Thanks.
public static void main(String[] args) {
SortOf one = new SortOf();
SortOf two = new SortOf();
one.code = "a";
one.bal = 2;
one.rate = 3;
two.code = "abc";
two.bal = 2;
two.rate = 1;
System.out.println(one.equals(two));
System.out.println(one.hashCode() == two.hashCode());
}
Given:
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 fullfil the equals() and hashCode() contracts for this class? (Choos 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 and D are given as the correct answers.
I agree C is correct. But, If I create the SortOf class with answer D and run the following code, I get true and false. So, the hashCode() returns a different value when the objects are equal. Does that mean the correct answer is C only?
Thanks.
public static void main(String[] args) {
SortOf one = new SortOf();
SortOf two = new SortOf();
one.code = "a";
one.bal = 2;
one.rate = 3;
two.code = "abc";
two.bal = 2;
two.rate = 1;
System.out.println(one.equals(two));
System.out.println(one.hashCode() == two.hashCode());
}